说明
玩转webpack
课程学习笔记。
JS 文件的压缩
内置了 uglifyjs-webpack-plugin
,打包会自动压缩js
CSS 文件的压缩
npm i optimize-css-assets-webpack-plugin -D
1、使用 optimize-css-assets-webpack-plugin
npm i cssnano -D
2、同时使用 cssnano
const path = require('path'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin'); module.exports = { entry: { index: './src/index.js', search: './src/search.js' }, output: { path: path.join(__dirname, 'dist'), filename: '[name]_[chunkhash].js' }, mode: 'production', plugins: [ new MiniCssExtractPlugin({ filename: '[name]_[contenthash:8].css' }), new OptimizeCSSAssetsPlugin({ assetNameRegExp: /\.css$/g, cssProcessor: require('cssnano') }) ] };
html 文件的压缩
1、在src
文件里新建index.html
,search.html
文件
index.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> </body> </html>
search.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <div id="root"></div> </body> </html>
npm i html-webpack-plugin -D
2、修改 html-webpack-plugin
,设置压缩参数
const path = require('path'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: { index: './src/index.js', search: './src/search.js' }, output: { path: path.join(__dirname, 'dist'), filename: '[name]_[chunkhash].js' }, mode: 'production', plugins: [ new MiniCssExtractPlugin({ filename: '[name]_[contenthash:8].css' }), new HtmlWebpackPlugin({ template: path.join(__dirname, 'src/index.html'), filename: 'index.html', chunks: ['index'], inject: true, minify: { html5: true, collapseWhitespace: true, preserveLineBreaks: false, minifyCSS: true, minifyJS: true, removeComments: false } }), new HtmlWebpackPlugin({ template: path.join(__dirname, 'src/search.html'), filename: 'search.html', chunks: ['search'], inject: true, minify: { html5: true, collapseWhitespace: true, preserveLineBreaks: false, minifyCSS: true, minifyJS: true, removeComments: false } }) ] };