引入压缩插件,分别对 Js、Html、Css 进行压缩,Js压缩:UglifyJsPlugin,Html压缩HtmlWebpackPlugin,提取公共资源:CommonsChunkPlugin,提取css并压缩:ExtractTextPlugin 。
配置全局变量
告诉 webpack 我要发布 production 了,按照 production 方式去打包。
new webpack.DefinePlugin({
'process.env': {
//注意一个单引号一个双引号…… 这里是要将 "production" 替换到文件里面
NODE_ENV: '"production"'
}
})
注意 devtool 中的 source-map。
可以试一下,当开启 devtool打包后的文件
devtool: "inline-source-map"
ExtractTextPlugin提取css并压缩
使 css 剥离 js 文件, 将 css 单独打包。
依赖插件 npm install --save-dev extract-text-webpack-plugin 先安装再使用
var ExtractTextPlugin = require('extract-text-webpack-plugin');
//在 plugins 中配置
plugins: [ new ExtractTextPlugin('[name].[contenthash].css') ]
把 css 单独打包出来,免得以后只修改 css 导致 浏览器端 js 的缓存也失效了。
这里使用了 contenthash, webpack 会按照内容去生成 hash 值。
压缩, 去除注释
//在 plugins 中添加
new webpack.optimize.UglifyJsPlugin({
comments: false, //去掉注释
compress: {
warnings: false //忽略警告,要不然会有一大堆的黄色字体出现……
}
})
开启 gzip 压缩
var CompressionWebpackPlugin = require('compression-webpack-plugin');
//在 plugin 中添加
new CompressionWebpackPlugin({ //gzip 压缩
asset: '[path].gz[query]',
algorithm: 'gzip',
test: new RegExp(
'\\.(js|css)$' //压缩 js 与 css
),
threshold: 10240,
minRatio: 0.8
})
压缩 html, 自动添加上面生成的静态资源。
var HtmlWebpackPlugin = require('html-webpack-plugin');
new HtmlWebpackPlugin({
filename: 'react.html', //生成的文件,从 output.path 开始 output.path + "/react.html"
template: '../client/react.html', //读取的模板文件,这个路径是相对于当前这个配置文件的
inject: true, // 自动注入
minify: {
removeComments: true, //去注释
collapseWhitespace: true, //压缩空格
removeAttributeQuotes: true //去除属性引用
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
//必须通过上面的 CommonsChunkPlugin 的依赖关系自动添加 js,css 等
chunksSortMode: 'dependency'
})
项目中的配置
// http://vuejs.github.io/vue-loader/en/workflow/production.html
new webpack.DefinePlugin({
'process.env': env
}),
new UglifyJsPlugin({
uglifyOptions: {
compress: {
warnings: false
}
},
sourceMap: config.build.productionSourceMap,
parallel: true
}),
// extract css into its own file
new ExtractTextPlugin({
filename: utils.assetsPath('css/[name].[contenthash].css'),
// Setting the following option to `false` will not extract CSS from codesplit chunks.
// Their CSS will instead be inserted dynamically with style-loader when the codesplit chunk has been loaded by webpack.
// It's currently set to `true` because we are seeing that sourcemaps are included in the codesplit bundle as well when it's `false`,
// increasing file size: https://github.com/vuejs-templates/webpack/issues/1110
allChunks: true,
}),
// Compress extracted CSS. We are using this plugin so that possible
// duplicated CSS from different components can be deduped.
new OptimizeCSSPlugin({
cssProcessorOptions: config.build.productionSourceMap
? { safe: true, map: { inline: false } }
: { safe: true }
}),
// generate dist index.html with correct asset hash for caching.
// you can customize output by editing /index.html
// see https://github.com/ampedandwired/html-webpack-plugin
new HtmlWebpackPlugin({
filename: process.env.NODE_ENV === 'testing'
? 'index.html'
: config.build.index,
template: 'index.html',
inject: true,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
// more options:
// https://github.com/kangax/html-minifier#options-quick-reference
},
// necessary to consistently work with multiple chunks via CommonsChunkPlugin
chunksSortMode: 'dependency'
}),
// new BundleAnalyzerPlugin(),
// keep modules.id stable when vendor modules does not change
new webpack.HashedModuleIdsPlugin(),
// enable scope hoisting
new webpack.optimize.ModuleConcatenationPlugin(),
// split vendor js into its own file
new webpack.optimize.CommonsChunkPlugin({
name: 'vendor',
minChunks (module) {
// any required modules inside node_modules are extracted to vendor
return (
module.resource &&
/\.js$/.test(module.resource) &&
module.resource.indexOf(
path.join(__dirname, '../node_modules')
) === 0
)
}
}),
// extract webpack runtime and modules manifest to its own file in order to
// prevent vendor hash from being updated whenever app bundle is updated
new webpack.optimize.CommonsChunkPlugin({
name: 'manifest',
minChunks: Infinity
}),
// This instance extracts shared chunks from code splitted chunks and bundles them
// in a separate chunk, similar to the vendor chunk
// see: https://webpack.js.org/plugins/commons-chunk-plugin/#extra-async-commons-chunk
new webpack.optimize.CommonsChunkPlugin({
name: 'app',
async: 'vendor-async',
children: true,
minChunks: 3
}),
// copy custom static assets
new CopyWebpackPlugin([
{
from: path.resolve(__dirname, '../static'),
to: config.build.assetsSubDirectory,
ignore: ['.*']
}
])