我正在尝试创建我的 React 项目的生产版本,但它选择了错误的配置。
在开发版本中,我使用的是 HMR(热模块更换)。这是在 .babelrc 中配置的,位于 env > development > plugins
下。
添加额外节点 env > production
时,它似乎被忽略了。它仍然使用带有 HMR 的开发配置,这会导致错误:
Uncaught Error: locals[0] does not appear to be a
module
object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by usingenv
section in Babel configuration. See the example in README: https://github.com/gaearon/react-transform-hmr
当然,我已经检查了这些信息,但一切似乎都是正确的。 当我从 .babelrc 的开发配置中删除 HMR 插件时,它可以工作,证明它确实在使用开发配置而不是生产配置。 这是我的文件:
package.json
{
"name": "myproject",
"main": "index.js",
"scripts": {
"serve": "cross-env NODE_ENV=development webpack-dev-server --content-base bin/ --devtool eval --progress --colors --hot --inline",
"deploy": "cross-env NODE_ENV=production BABEL_ENV=production webpack -p --config webpack.production.config.js"
}
//dependencies omitted in this example
}
.babelrc
{
"presets": ["react", "es2015", "stage-0"],
"plugins": [
["transform-decorators-legacy"]
],
"env": {
"development": {
"plugins": [
["react-transform", {
"transforms": [{
"transform": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}]
}]
]
},
"production": {
"plugins": []
}
}
}
如您在 package.json > scripts > deploy
中所见,我什至明确地将 BABEL_ENV 设置为“生产”。
为什么会这样?我如何确保生产构建忽略 HMR 插件?
顺便说一句,搜索通常会导致 issue #5 on the React-transform-HMR Github page ,这是一个没有明确解决方案的长线程。
编辑 2016.03.30:根据要求添加我的 webpack 配置的 Babel 部分。 编辑 2016.04.06:根据要求添加整个 webpack 文件。
webpack.production.config.js
require('es6-promise').polyfill();
var path = require('path');
module.exports = {
entry: './main.jsx',
context: __dirname + path.sep + 'src',
output: {
path: path.resolve(__dirname, './bin'),
filename: 'index.js'
},
devServer: {
port: 3333
},
module: {
loaders: [
{
test: /\.js(x?)$/,
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-0'],
plugins: [['transform-decorators-legacy']]
}
},
{
test: /\.css$/,
loader: "style!css"
},
{
test: /\.scss$/,
exclude: /(node_modules|bower_components)/,
loader: 'style-loader!css-loader!sass-loader?sourceMap'
}
]
}
};
最佳答案
唯一对我有用的是我写的 -
process.env.NODE_ENV = 'production';
在我的 webpack.config.prod.js 文件的开头。
关于javascript - 为什么 React 应用程序的生产构建(使用 Webpack 和 Babel)使用错误的开发环境和 HMR,这会导致错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36153628/