Rollup + React 17 与新的 JSX 转换 - “React 未定义”

Noa*_*den 10 javascript reactjs react-router rollupjs

我正在尝试使用 Rollup 和几个 create-react-app 应用程序构建微前端架构原型。但是,当我在本地使用yarn link容器应用程序的外部应用程序时,遇到以下错误:

ReferenceError:React 未定义

23500 | 23500 return / # PURE /React.createElement("div", { | ^ 23501 | id: "container", 23502 | className: "flex flex-col h-screen" 23503 | }, / # PURE /React.createElement(BrowserRouter , null, / # PURE /React.createElement(Header, {

我认为这是因为我们没有React在每个组件/文件的顶部导入,因为 React 17 的新 JSX Transform 允许您不必这样做。我真的希望能够构建我们的微前端包,而不必在每个文件中导入 React,有没有办法做到这一点?

这是 rollup.config.js:

import babel from 'rollup-plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import external from 'rollup-plugin-peer-deps-external';
import postcss from 'rollup-plugin-postcss';
import resolve from '@rollup/plugin-node-resolve';
import image from '@rollup/plugin-image';
import visualizer from 'rollup-plugin-visualizer';
import includePaths from 'rollup-plugin-includepaths';
import replace from '@rollup/plugin-replace';
import pkg from './package.json';

const extensions = ['.js', '.jsx', '.ts', '.tsx'];

export default {
  input: './src/App.jsx',
  output: [
    {
      file: pkg.main,
      format: 'cjs',
    },
    {
      file: pkg.module,
      format: 'esm',
    },
  ],
  plugins: [
    external(),
    postcss(),
    resolve({
      mainFields: ['module', 'main', 'jsnext:main', 'browser'],
      extensions,
    }),
    image(),
    visualizer(),
    includePaths({ paths: ['./'] }),
    replace({
      'process.env.NODE_ENV': JSON.stringify('development'),
    }),
    babel({
      exclude: 'node_modules/**',
      plugins: [
        [
          'module-resolver',
          {
            root: ['src'],
          },
        ],
      ],
      presets: ['@babel/preset-react'],
    }),
    commonjs(),
  ],
};
Run Code Online (Sandbox Code Playgroud)

小智 5

在 tsconfig.json 中添加以下代码

{
  "compilerOptions": {
    "jsx": "react-jsx",
  }
}


Run Code Online (Sandbox Code Playgroud)


Hen*_*ody 5

{ runtime: "automatic" }通过添加到预设来修复此问题@babel/preset-react

来自预设反应运行时文档

automaticauto 导入 JSX 转换为的函数。classic不自动导入任何东西。

在 React 帖子中还提到了新的 JSX 转换

目前,旧的转换{"runtime": "classic"}是默认选项。要启用新的转换,您可以将其{"runtime": "automatic"}作为选项传递给@babel/plugin-transform-react-jsx@babel/preset-react

这是一个示例:

{
    // ...
    plugins: [
        // ...
        babel({
            // ...
            presets: [
                // ...
                ["@babel/preset-react", { runtime: "automatic" }],
            ]
        })
    ]
}
Run Code Online (Sandbox Code Playgroud)