facebook / react

The library for web and native user interfaces.
https://react.dev
MIT License
229.4k stars 46.98k forks source link

Bug: react 16 and 17 not working in ESM env with TypeScript #25857

Closed unional closed 1 year ago

unional commented 1 year ago

React version: 16 and 17

Reference: https://github.com/vitest-dev/vitest/issues/2468

Steps To Reproduce

  1. using react 16/17 in a ESM project (and e.g. with vite)
  2. using react-jsx typescript setting

There will be error of "Cannot find module" for react/jsx-runtime

The current behavior

Not working, needs workaround

The expected behavior

Should work.

I can help with PR to add the exports field to React 16/17.

idler8 commented 1 year ago

look it https://github.com/reactjs/reactjs.org/issues/5659

eps1lon commented 1 year ago

It doesn't look like this bug report has enough info for one of us to reproduce it.

Please provide a CodeSandbox (https://react.new), or a link to a repository on GitHub.

Here are some tips for providing a minimal example: https://stackoverflow.com/help/mcve

unional commented 1 year ago

The support of ESM was added in 18, it is not there in 16 and 17.

unional commented 1 year ago

Here is a repro: https://github.com/cyberuni/react-16-vite-ts-issue

pnpm i
pnpm vitest
unional commented 1 year ago

Adding this to packages/react/package.json will fix the issue:

  "exports": {
    ".": {
      "default": "./index.js"
    },
    "./package.json": "./package.json",
    "./jsx-runtime": "./jsx-runtime.js",
    "./jsx-dev-runtime": "./jsx-dev-runtime.js",
    "./src/*": "./src/*"
  },

However I can't modify the code and commit because when trying to do a yarn install on v16.14.0, I got:

Response code 404 (Not Found) for https://github.com/electron/electron/releases/download/v9.1.0/electron-v9.1.0-darwin-arm64.zip
unional commented 1 year ago

dup of #20235

with some workarounds: https://github.com/facebook/react/issues/20235#issuecomment-1061708958 https://github.com/facebook/react/issues/20235#issuecomment-1048182768

unional commented 1 year ago

Note that the workaround for webpack does not work for vitest if the issue comes from a dependency using react-jsx option.

This is because vite uses esbuild to compile individual dependency files, and there is no way to use plugin to perform aliasing.

The workaround in vitest is using dependency inlining:

{
  test: {
    deps: {
      inline: ['dep-package']
    }
  }
}