Why does production build of React app (with Webpack and Babel) use wrong development env with HMR, which causes errors?

馋奶兔 提交于 2019-11-30 11:37:15

The only thing that worked for me, is that I wrote -

process.env.NODE_ENV = 'production';

at the beginning of my webpack.config.prod.js file.

It seems that no matter what Babel keeps using the development section of the env value specified in .babelrc. What solved the problem for me, was to use name other than 'development' and set that as the value of BABEL_ENV.

"env": {
    "dev": {
        "plugins": [
        ]
    },
    "production": {
    }
}

I use separate conf for development. In plugins I have:

new webpack.DefinePlugin({
  'process.env': {
    'NODE_ENV': JSON.stringify('development'),
    'BABEL_ENV': JSON.stringify('dev')
  }
}),

& in shell means that it will run in the background, so maybe your variable declaration is not caught by the build stuff that happens at the same time. The good thing is that you can just prepend the command with the variable declarations.

You could simplify the commands like this:

"serve": "NODE_ENV=development webpack-dev-server --content-base bin/ --devtool eval --progress --colors --hot --inline",
"deploy": "NODE_ENV=production BABEL_ENV=production webpack -p --config webpack.production.config.js"

You can just use the babel-preset-react-hmre.

.babelrc

{
    "presets": ["react", "es2015", "stage-0"],
    "plugins": [
        "transform-decorators-legacy"
    ],
    "env": {
        "development": {
            "presets": ["react-hmre"]
        }
    }
}

webpack

    {
        test: /\.js(x?)$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: {
            presets: ['es2015', 'react', 'stage-0'],
            plugins: ['transform-decorators-legacy'],
            env: {
              development: {
                presets: ['react-hmre']
              }
            }
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!