webpack内置了 uglifyjs-webpack-plugin,自动帮我们进行代码压缩
使⽤ optimize-css-assets-webpack-plugin,同时需要安装cssnano
配置
var OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = {
module: {
rules: [
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
}
]
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name]_[contenthash:8].css'
}),
new OptimizeCssAssetsPlugin({
assetNameRegExp: /\.optimize\.css$/g,
cssProcessor: require('cssnano'),
cssProcessorPluginOptions: {
preset: ['default', { discardComments: { removeAll: true } }],
},
canPrint: true
})
]
};
new MiniCssExtractPlugin({
filename: ‘[name]_[contenthash:8].css’
}),
修改 html-webpack-plugin,设置压缩参数
'use strict';
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
search: './src/search.js'
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name]_[chunkhash:8].js'
},
mode: 'production',
plugins: [
new MiniCssExtractPlugin({
filename: '[name]_[contenthash:8].css'
}),
new OptimizeCSSAssetsPlugin({
assetNameRegExp: /\.css$/g,
cssProcessor: require('cssnano')
}),
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src/search.html'),
filename: 'search.html',
chunks: ['search'],
inject: true,
minify: {
html5: true,//Parse input according to HTML5 specifications
collapseWhitespace: true,//Collapse white space that contributes to text nodes in a document tree
preserveLineBreaks: false,//Always collapse to 1 line break (never remove it entirely) when whitespace between tags include a line break. Must be used in conjunction with collapseWhitespace=true
minifyCSS: true,//Minify CSS in style elements and style attributes (uses clean-css)
minifyJS: true,//Minify JavaScript in script elements and event attributes (uses Terser)
removeComments: false//Strip HTML comments
}
})
]
};
每次构建的时候不会清理⽬录,造成构建的输出⽬录 output ⽂件越来越多,难以找出新生成的文件
rm -rf ./dist && webpack
rimraf ./dist && webpack
避免构建前每次都需要⼿动删除 dist,通过使用clean-webpack-plugin插件进行,默认会删除 output 指定的输出⽬录。
module.exports = {
entry: {
app: './src/app.js',
search: './src/search.js'
},
output: {
filename: '[name][chunkhash:8].js',
path: __dirname + '/dist'
},
plugins: [
new CleanWebpackPlugin()
};