Webpack 打包 - 10. 压缩CSS
使用 optimize-css-assets-webpack-plugin 插件压缩 CSS文件。
1.文件结构
2.安装 optimize-css-assets-webpack-plugin (根据自己环境安装合适的版本)
$ npm i postcss-loader@3.0.0 postcss-preset-env@6.7.0 -D
3. a.css
#box1 { width: 100px; height: 100px; background-color: pink; display: flex; backface-visibility: hidden; }
b.css
#box2 { width: 200px; height: 200px; background-color: deeppink; }
index.js
import '../css/a.css';
import '../css/b.css';
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>webpack</title> </head> <body> <div id="box1"></div> <div id="box2"></div> </body> </html>
webpack.config.js
const {resolve} = require('path') const HtmlWebpackPlugin = require('html-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin') //设置 nodejs 环境变量 // process.env.NODE_ENV = 'development' module.exports = { entry: './src/js/index.js', output: { filename: "js/built.js", path: resolve(__dirname, 'build') }, module: { rules: [ { test: /\.css$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', { loader: "postcss-loader", // 修改loader的配置 options: { ident: 'postcss', plugins: () => [ //postcss 的插件 require('postcss-preset-env')() ] } } ] } ] }, plugins: [ new HtmlWebpackPlugin({ template: "./src/index.html" }), new MiniCssExtractPlugin({ filename: 'css/built.css' }), // 压缩css new OptimizeCssAssetsWebpackPlugin() ], mode: "development" }
4.打包
$ webpack
5.
生成的 built.css 文件已经被压缩
end~