JS压缩
- webpack内置了
uglifyjs-webpack-plugin
CSS压缩
- 使用
css-minimizer-webpack-plugin
- 下载包
npm i css-minimizer-webpack-plugin -D
- 下载包
同时使用
cssnano
- css的预处理器
- 下载包:
npm i cssnano -D
// webpack.prod.js
'use strict';
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader']
},
{
test: /\.less$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'less-loader'],
},
{
test: /\.(scss|sass)$/,
use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
},
},
plugins: [
new MiniCssExtractPlugin({
filename: '[name]_[contenthash:8].css'
}),
new CssMinimizerPlugin(),
],
mode: 'production',
}
html压缩
使用
html-webpack-plugin
,设置压缩参数- 下载包:
npm i html-webpack-plugin -D
- 下载包:
// webpack.config.js
'use strict';
const path = require('path');
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
plugins: [
// 多个html就,写多个HtmlWebpackPlugin,然后把index换成对应的html的名称
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src/index.html'),
filename: 'index.html',
chunk: ['index'],
inject: true,
minify: {
html5: true,
collapseWhitespace: true,
preserveLineBreaks: false,
minifyCSS: true,
minifyJS: true,
removeComments: false
}
})
],
mode: 'production',
}