Rollup.js | 解决打包react项目报错

报错信息

1
2
3
4
5
react.development.js:12 Uncaught ReferenceError: process is not defined
at react.development.js:12
at createCommonjsModule (bundle.js:6)
at react.production.min.js:23
at index.js:10

process对象是nodejs的环境变量,浏览器端是没有的。
解决办法,在打包后的bundle.js里var一个process对象,例如

1
2
3
4
5
var process = {
env: {
NODE_ENV: 'production'
}
}

但是每次重新构建bundle.js后,又要重新添加,所以可以在rollup.config.js里配置,

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'

const Global = `var process = {
env: {
NODE_ENV: 'production'
}
}`

export default {
input: pathResolve('src/index.js'),
output: {
name: 'bundle',
file: pathResolve("dist/js/bundle.js"),
format: 'iife',//immediately-invoked function expression — suitable for <script> tags
sourcemap: true,
banner: Global//output.banner属性的作用是在打包后的文件顶部添加值。
},
plugins: [resolve(), commonjs()]

或者rollup.config.js配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import replace from "@rollup/plugin-replace";
export default {
input: pathResolve('src/index.js'),
output: {
name: 'bundle',
file: pathResolve("dist/js/bundle.js"),
format: 'iife',//immediately-invoked function expression — suitable for <script> tags
sourcemap: true,
},
plugins: [
resolve(), // tells Rollup how to find date-fns in node_modules

babel({
babelHelpers: "bundled",
exclude: "**/node_modules/**",
}),
commonjs(), // converts date-fns to ES modules
replace({
"process.env.NODE_ENV": JSON.stringify("development"),
}),
]
};