javascript 如何将 React 置于生产模式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47912805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to put React in production mode?
提问by
I tried using the solution from herebut the icon is still read indicating dev mode.
我尝试使用此处的解决方案,但仍会读取指示开发模式的图标。
Here is my current file with updates from the answer below:
这是我当前的文件,其中包含以下答案的更新:
const path = require('path');
const SRC_DIR = path.join(__dirname, '/client-react/src');
const DIST_DIR = path.join(__dirname, '/client-react/dist');
const webpack = require('webpack')
module.exports = {
entry: `${SRC_DIR}/index.jsx`,
output: {
filename: 'bundle.js',
path: DIST_DIR
},
plugins: [
new webpack.DefinePlugin({'process.env': {NODE_ENV: JSON.stringify('production')} })
],
module: {
loaders: [
{
test: /\.jsx?/,
include: SRC_DIR,
loader: 'babel-loader',
query: {
plugins: ["transform-object-rest-spread", "transform-class-properties"],
presets: ['react', 'es2015']
}
}
]
}
};
回答by Webars
If you use Webpack 4, you don't need to change webpack.config.js. It remains the same in both development and production modes.
如果使用 Webpack 4,则无需更改webpack.config.js. 它在开发和生产模式中都保持不变。
The only thing needed is in your package.json:
唯一需要的是在您的package.json:
"scripts": {
"dev": "webpack --mode development",
"build": "webpack --mode production"
}
Having this, to create a development bundle:
有了这个,创建一个开发包:
npm run dev
Production bundle:
生产捆绑:
npm run build
回答by margaretkru
When you want to build your app in production mode, you should use webpackproduction shortcut. Like this:
当你想在生产模式下构建你的应用程序时,你应该使用webpack生产快捷方式。像这样:
webpack -p
webpack -p
This will enable webpackoptimize optionsto minify your JS. See more detailed explanation of webpackflags on this SO answer.
这将启用webpack优化选项以缩小您的 JS。请参阅此 SO answer 上的webpack标志的更详细说明。
回答by Chris
Webpack plugins need to be put under the pluginskey in module.exports.
的WebPack插件需要下放到plugins关键module.exports。
https://webpack.github.io/docs/using-plugins.html#built-in-plugins
https://webpack.github.io/docs/using-plugins.html#built-in-plugins
Try this:
试试这个:
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify('production') }
}),
]
}
回答by Arnold Gandarillas
Had the same error so to fix it I did this:
有同样的错误,所以为了修复它,我这样做了:
package.json
包.json
"scripts": {
"build": "NODE_ENV=production webpack --progress --colors",
"start": "NODE_ENV=development webpack-dev-server --progress --colors"
}
webpack.config.js
webpack.config.js
const env = process.env.NODE_ENV
module.exports = {
plugins: [
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env)
})
]
}
It should work for sure.
它应该肯定有效。
HereI have some configuration that you can try to optimize your build.
这里我有一些配置,您可以尝试优化构建。

