Skip to content

React build issue edge case #7640

@js2702

Description

@js2702

Describe the bug

When building an application with Vite that uses a React external library we've encountered with a very strange issue that we think it's related to the tree shacking or bundling that Vite uses. Webpack works with the same library.
We've created a minimal reproduction example.

The issue happens when one of the transitive libraries of the main React library creates a variable named React (In the example in the library react-transitive-lib-2). This can happen in certain libraries that are CommonJS.
For example this CommonJS library code that is autogenerated:

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var React = _interopDefault(require('react'));

Another of the transitive dependencies may use something like the following (in the example react-transitive-lib-1):

import React from 'react';
console.log(React.version);

Which in combination when creating the final build of the library it gets bundled as:

import * as React$1 from 'react';
import React__default, { useEffect } from 'react';

If after those imports some code uses React__default.createElement the browser returns that React is undefined.
The interesting thing is that if React__default is manually renamed in the bundle to React$1__default it works ok.
Another interesting thing is that createElement is the only property of React that fails when accessing it. If one does React__default.{some_property} it works fine.

We've tried to reproduce it in a minimal example what happens when using a combination of React libraries.

So when using this React library in the Vite React scaffolding app it just breaks. If we use the same library in a create-react-app it works fine.

Is this an error with Vite? Rollup? Esbuild?

Reproduction

Clone the code and follow the readme

System Info

System:
    OS: macOS 12.3.1
    CPU: (16) x64 Intel(R) Core(TM) i7-10700K CPU @ 3.80GHz
    Memory: 3.32 GB / 32.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 17.8.0 - /usr/local/bin/node
    Yarn: 1.22.17 - /usr/local/bin/yarn
    npm: 8.5.5 - /usr/local/bin/npm
  Browsers:
    Brave Browser: 100.1.37.111
    Chrome: 100.0.4896.75
    Firefox: 98.0.2
    Safari: 15.4

Used Package Manager

yarn

Logs

No response

Validations

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions