webpack高级概念,CSS文件的代码分割 与压缩(系列八)
我们之前写的css文件都会被打包进js文件中,要想把css单独打包成一个css文件该怎么做呢?
这个时候就需要用到 MiniCssExtractPlugin
开发环境用不到这个功能(因为这个东西不支持热模块更新,样式更改自动替换,不用刷新页面),一般都是用在生产环境中。
安装: npm install --save-dev mini-css-extract-plugin
如何将打包成的css文件压缩呢,需要用到optimize-css-assets-webpack-plugin
安装;npm install optimize-css-assets-webpack-plugin --save-dev
webpack.dev.js,开发环境的style-loader不需要替换
const webpack = require('webpack'); const merge = require('webpack-merge'); const commonConfig = require('./webpack.common.js'); const devConfig = { mode: 'development', devtool: 'cheap-module-eval-source-map', devServer: { contentBase: './dist', open: true, port: 8080, hot: true }, module: { rules: [{ test: /\.scss$/, use: [ 'style-loader', { loader: 'css-loader', options: { importLoaders: 2 } }, 'sass-loader', 'postcss-loader' ] }, { test: /\.css$/, use: [ 'style-loader', 'css-loader', 'postcss-loader' ] }] }, plugins: [ new webpack.HotModuleReplacementPlugin() ], // 树摇 optimization: { usedExports: true } } module.exports = merge(commonConfig, devConfig);
webpack.prod.js, 生产环境,生产环境默认有树摇功能,对css模块导入会去除,需要在package.json中配置下,禁止树摇css模块
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin"); const merge = require('webpack-merge'); const commonConfig = require('./webpack.common.js'); const prodConfig = { mode: 'production', devtool: 'cheap-module-source-map', module: { rules:[{ test: /\.scss$/, use: [ MiniCssExtractPlugin.loader, //修改loader,将原来的style-lodader替换,不然没效果 { loader: 'css-loader', options: { importLoaders: 2 } }, 'sass-loader', 'postcss-loader' ] }, { test: /\.css$/, use: [
MiniCssExtractPlugin.loader, 'css-loader', 'postcss-loader' ] }] }, optimization: { minimizer: [new OptimizeCSSAssetsPlugin({})] }, plugins: [ new MiniCssExtractPlugin({ //配置插件,两个属性都是可选的,配置打包后css名称 filename: '[name].css', chunkFilename: '[name].chunk.css' }) ] } module.exports = merge(commonConfig, prodConfig);
package.json, 生产环境默认有树摇功能,对css模块导入会去除,需要在package.json中配置下,禁止树摇css模块
{ "name": "lesson", "sideEffects": [ "*.css" ], "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "dev-build": "webpack --config ./build/webpack.dev.js", "dev": "webpack-dev-server --config ./build/webpack.dev.js", "build": "webpack --config ./build/webpack.prod.js" },
index.js入口文件
import './style.css'; import './style1.css'; console.log('hello world');
style.css
body {
background: green;
}
style1.css
body { font-size: 100px; }
这样打包(npm run build)之后,css会被单独打包成一个css文件。并且代码是压缩的