我是webpack的新手,我发现在生产版本中我们可以减少整体代码的大小。目前,webpack构建大约8MB的文件,而main.js构建大约5MB的文件。如何减少生产构建中的代码大小?我从互联网上找到了一个样本webpack配置文件,并为我的应用程序进行了配置,然后运行npm run build并开始构建它,并在./dist/目录中生成了一些文件。
npm run build
./dist/
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
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
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] } };
在观察到这个问题的观众数量之后,我决定总结Vikramaditya和Sandeep的答案。
要生成生产代码,您首先要创建的是使用优化包(例如,
new webpack.optimize.CommonsChunkPlugin('common.js'), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.AggressiveMergingPlugin()
然后,在package.json文件中,您可以使用此生产配置来配置构建过程
"scripts": { "build": "NODE_ENV=production webpack --config ./webpack.production.config.js" },
现在您必须运行以下命令来启动构建
根据我的生产构建配置,webpack会将源构建到./dist目录。
./dist
现在,您的UI代码将在./dist/目录中可用。配置服务器以将这些文件用作静态资产。做完了!