node.js Webpack 如何构建生产代码以及如何使用它
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35054082/
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
Webpack how to build production code and how to use it
提问by Gilson PJ
I am very new to webpack, I found that in production build we can able to reduce the size of overall code.
Currently webpack builds around 8MB files and main.js around 5MB.
How to reduce the size of code in production build?
I found a sample webpack configurtion file from internet and I configured for my application and I run npm run buildand its started building and it generated some files in ./dist/directory.
我对 webpack 很陌生,我发现在生产构建中我们可以减少整体代码的大小。目前 webpack 构建了大约 8MB 的文件和大约 5MB 的 main.js。如何减少生产构建中的代码大小?我从互联网上找到了一个示例 webpack 配置文件,并为我的应用程序进行了配置,然后运行npm run build并开始构建它并在./dist/目录中生成了一些文件。
- Still these files are heavy(same as development version)
- How to use these files? Currently I am using webpack-dev-server to run the application.
- 这些文件仍然很重(与开发版本相同)
- 如何使用这些文件?目前我正在使用 webpack-dev-server 来运行该应用程序。
package.json file
package.json 文件
{
"name": "MyAPP",
"version": "0.1.0",
"description": "",
"main": "src/server/server.js",
"repository": {
"type": "git",
"url": ""
},
"keywords": [
],
"author": "Iam",
"license": "MIT",
"homepage": "http://example.com",
"scripts": {
"test": "",
"start": "babel-node src/server/bin/server",
"build": "rimraf dist && NODE_ENV=production webpack --config ./webpack.production.config.js --progress --profile --colors"
},
"dependencies": {
"scripts" : "", ...
},
"devDependencies": {
"scripts" : "", ...
}
}
webpack.config.js
webpack.config.js
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var public_dir = "src/frontend";
var ModernizrWebpackPlugin = require('modernizr-webpack-plugin');
module.exports = {
devtool: 'eval-source-map',
entry: [
'webpack-hot-middleware/client?reload=true',
path.join(__dirname, public_dir , 'main.js')
],
output: {
path: path.join(__dirname, '/dist/'),
filename: '[name].js',
publicPath: '/'
},
plugins: [
plugins
],
module: {
loaders: [loaders]
}
};
webpack.production.config.js
webpack.production.config.js
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var public_dir = "src/frontend";
var ModernizrWebpackPlugin = require('modernizr-webpack-plugin');
console.log(path.join(__dirname, 'src/frontend' , 'index.html'));
module.exports = {
devtool: 'eval-source-map',
entry: [
'webpack-hot-middleware/client?reload=true',
path.join(__dirname, 'src/frontend' , 'main.js')
],
output: {
path: path.join(__dirname, '/dist/'),
filename: '[name].js',
publicPath: '/'
},
plugins: [plugins],
resolve: {
root: [path.resolve('./src/frontend/utils'), path.resolve('./src/frontend')],
extensions: ['', '.js', '.css']
},
module: {
loaders: [loaders]
}
};
采纳答案by Gilson PJ
After observing number of viewers to this question I decided to conclude an answer from Vikramaditya and Sandeep.
在观察了这个问题的观众数量后,我决定总结 Vikramaditya 和 Sandeep 的回答。
To build the production code the first thing you have to create is production configuration with optimization packages like,
要构建生产代码,您必须创建的第一件事是带有优化包的生产配置,例如,
new webpack.optimize.CommonsChunkPlugin('common.js'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
Then in the package.json file you can configure the build procedure with this production configuration
然后在 package.json 文件中,您可以使用此生产配置配置构建过程
"scripts": {
"build": "NODE_ENV=production webpack --config ./webpack.production.config.js"
},
now you have to run the following command to initiate the build
现在您必须运行以下命令来启动构建
npm run build
As per my production build configuration webpack will build the source to ./distdirectory.
根据我的生产构建配置,webpack 会将源构建到./dist目录。
Now your UI code will be available in ./dist/directory. Configure your server to serve these files as static assets. Done!
现在您的 UI 代码将在./dist/目录中可用。配置您的服务器以将这些文件作为静态资产提供服务。完毕!
回答by sandeep
You can add the plugins as suggested by @Vikramaditya. Then to generate the production build. You have to run the the command
您可以按照@Vikramaditya 的建议添加插件。然后生成生产版本。你必须运行命令
webpack -p --config ./webpack.production.config.js
The -ptells webpack to generate a production build. You have to change the build script in package.jsonto include the production flag.
该-p通知的WebPack生成一个生产版本。您必须更改package.json 中的构建脚本以包含生产标志。
回答by Vikramaditya
Use these plugins to optimize your production build:
使用这些插件来优化您的生产构建:
new webpack.optimize.CommonsChunkPlugin('common'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
I recently came to know about compression-webpack-pluginwhich gzips your output bundle to reduce its size. Add this as well in the above listed plugins list to further optimize your production code.
我最近开始了解compression-webpack-plugin,它可以对输出包进行gzip 以减小其大小。在上面列出的插件列表中也添加它以进一步优化您的生产代码。
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0.8
})
Server side dynamic gzip compression is not recommended for serving static client-side files because of heavy CPU usage.
由于 CPU 使用率高,不建议将服务器端动态 gzip 压缩用于提供静态客户端文件。
回答by Siyuan Jiang
Just learning this myself. I will answer the second question:
自己学这个而已。我来回答第二个问题:
- How to use these files? Currently I am using webpack-dev-server to run the application.
- 如何使用这些文件?目前我正在使用 webpack-dev-server 来运行该应用程序。
Instead of using webpack-dev-server, you can just run an "express". use npm install "express" and create a server.js in the project's root dir, something like this:
您可以运行“express”而不是使用 webpack-dev-server。使用 npm install "express" 并在项目的根目录中创建一个 server.js,如下所示:
var path = require("path");
var express = require("express");
var DIST_DIR = path.join(__dirname, "build");
var PORT = 3000;
var app = express();
//Serving the files on the dist folder
app.use(express.static(DIST_DIR));
//Send index.html when the user access the web
app.get("*", function (req, res) {
res.sendFile(path.join(DIST_DIR, "index.html"));
});
app.listen(PORT);
Then, in the package.json, add a script:
然后,在 package.json 中,添加一个脚本:
"start": "node server.js"
Finally, run the app: npm run startto start the server
最后,运行应用程序:npm run start启动服务器
A detailed example can be seen at: https://alejandronapoles.com/2016/03/12/the-simplest-webpack-and-express-setup/(the example code is not compatible with the latest packages, but it will work with small tweaks)
详细示例见:https: //alejandronapoles.com/2016/03/12/the-simplest-webpack-and-express-setup/(示例代码与最新包不兼容,但可以使用小调整)
回答by Hayk Aghabekyan
You can use argvnpm module (install it by running npm install argv --save) for getting params in your webpack.config.js file and as for production you use -pflag "build": "webpack -p", you can add condition in webpack.config.js file like below
您可以使用argvnpm 模块(通过运行npm install argv --save安装它)来获取 webpack.config.js 文件中的参数,至于生产,您使用-pflag "build": "webpack -p",您可以在 webpack.config.js 文件中添加条件,如下所示
plugins: [
new webpack.DefinePlugin({
'process.env':{
'NODE_ENV': argv.p ? JSON.stringify('production') : JSON.stringify('development')
}
})
]
And thats it.
就是这样。
回答by Khalid Azam
This will help you.
这会帮助你。
plugins: [
new webpack.DefinePlugin({
'process.env': {
// This has effect on the react lib size
'NODE_ENV': JSON.stringify('production'),
}
}),
new ExtractTextPlugin("bundle.css", {allChunks: false}),
new webpack.optimize.AggressiveMergingPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
mangle: true,
compress: {
warnings: false, // Suppress uglification warnings
pure_getters: true,
unsafe: true,
unsafe_comps: true,
screw_ie8: true
},
output: {
comments: false,
},
exclude: [/\.min\.js$/gi] // skip pre-minified libs
}),
new webpack.IgnorePlugin(/^\.\/locale$/, [/moment$/]), //https://stackoverflow.com/questions/25384360/how-to-prevent-moment-js-from-loading-locales-with-webpack
new CompressionPlugin({
asset: "[path].gz[query]",
algorithm: "gzip",
test: /\.js$|\.css$|\.html$/,
threshold: 10240,
minRatio: 0
})
],
回答by Putzi San
In addition to Gilson PJ answer:
除了吉尔森 PJ 的回答:
new webpack.optimize.CommonsChunkPlugin('common.js'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
with
和
"scripts": {
"build": "NODE_ENV=production webpack -p --config ./webpack.production.config.js"
},
cause that the it tries to uglify your code twice. See https://webpack.github.io/docs/cli.html#production-shortcut-pfor more information.
因为它试图两次丑化你的代码。有关更多信息,请参阅https://webpack.github.io/docs/cli.html#production-shortcut-p。
You can fix this by removing the UglifyJsPlugin from plugins-array or add the OccurrenceOrderPlugin and remove the "-p"-flag. so one possible solution would be
您可以通过从 plugins-array 中删除 UglifyJsPlugin 或添加 OccurrenceOrderPlugin 并删除“-p”-flag 来解决此问题。所以一种可能的解决方案是
new webpack.optimize.CommonsChunkPlugin('common.js'),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin(),
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.optimize.AggressiveMergingPlugin()
and
和
"scripts": {
"build": "NODE_ENV=production webpack --config ./webpack.production.config.js"
},
回答by MatthiasSommer
If you have a lot of duplicate code in your webpack.dev.config and your webpack.prod.config, you could use a boolean isProdto activate certain features only in certain situations and only have a single webpack.config.js file.
如果您的 webpack.dev.config 和 webpack.prod.config 中有很多重复的代码,您可以使用布尔值isProd仅在某些情况下激活某些功能,并且只有一个 webpack.config.js 文件。
const isProd = (process.env.NODE_ENV === 'production');
if (isProd) {
plugins.push(new AotPlugin({
"mainPath": "main.ts",
"hostReplacementPaths": {
"environments/index.ts": "environments/index.prod.ts"
},
"exclude": [],
"tsConfigPath": "src/tsconfig.app.json"
}));
plugins.push(new UglifyJsPlugin({
"mangle": {
"screw_ie8": true
},
"compress": {
"screw_ie8": true,
"warnings": false
},
"sourceMap": false
}));
}
By the way: The DedupePluginplugin was removed from Webpack. You should remove it from your configuration.
顺便说一句:DedupePlugin插件已从 Webpack 中删除。您应该将其从配置中删除。
UPDATE:
更新:
In addition to my previous answer:
除了我之前的回答:
If you want to hide your code for release, try enclosejs.com. It allows you to:
如果您想隐藏您的代码以供发布,请尝试enclosejs.com。它允许您:
- make a release version of your application without sources
- create a self-extracting archive or installer
- Make a closed source GUI application
- Put your assets inside the executable
- 制作没有来源的应用程序的发布版本
- 创建自解压存档或安装程序
- 制作一个闭源 GUI 应用程序
- 将您的资产放在可执行文件中
You can install it with npm install -g enclose
你可以安装它 npm install -g enclose

