我正在尝试使用 Rollup 和几个 create-react-app 应用程序对微前端架构进行原型(prototype)设计。但是,当我在本地 yarn link
我的外部应用程序与容器应用程序,我遇到了以下错误:
ReferenceError: React 未定义
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 转换允许您不必这样做。我真的很想能够构建我们的微前端包,而不必在每个文件中导入 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(),
],
};
最佳答案
通过添加 { runtime: "automatic" }
修复此问题到@babel/preset-react
预设。
来自 preset-react runtime docs :
automatic
auto imports the functions that JSX transpiles to.classic
does not automatic import anything.
React post about the new JSX transform 中也提到过:
Currently, the old transform
{"runtime": "classic"}
is the default option. To enable the new transform, you can pass{"runtime": "automatic"}
as an option to@babel/plugin-transform-react-jsx
or@babel/preset-react
这是一个示例:
{
// ...
plugins: [
// ...
babel({
// ...
presets: [
// ...
["@babel/preset-react", { runtime: "automatic" }],
]
})
]
}
关于javascript - Rollup + React 17 与新的 JSX 转换 - "React is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67811412/