开始,按照我的webpack分模块文章配置好后(mini-css-extract-plugin不支持代码hmr热更新,所以只在生产模式进行配置),开始下面的配置

yarn add mini-css-extract-plugin css-minimizer-webpack-plugin

配置css分离出单独的文件

//文件名:webpack.prod.js
const { merge } = require('webpack-merge'); const ComConfig = require('./webpack.common'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const prodConfig = { mode: 'production', devtool: 'cheap-module-source-map', module: { rules: [ { test: /\.([sc|c])ss$/, use: [ MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader' ] } ] }, plugins: [ new MiniCssExtractPlugin({ filename: '[name].css', //直接引入的css chunkFilename: '[id].css', //间接引入的css }), ] } module.exports = merge(prodConfig, ComConfig)

配置css压缩

//文件名:webpack.prod.js
const { merge } = require('webpack-merge');
const ComConfig = require('./webpack.common');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');    //css压缩插件
const prodConfig = {
    mode: 'production',
    devtool: 'cheap-module-source-map',
    module: {
        rules: [
            {
                test: /\.([sc|c])ss$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    'sass-loader'
                ]
            }
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name].css',
            chunkFilename: '[id].css',
        }),
    ],
    optimization: {
        minimizer: [
            // For webpack@5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
            // `...`
            new CssMinimizerPlugin(),
        ],
    },
}
module.exports = merge(prodConfig, ComConfig)

如果开启了tree shaking,package.json中的sideEffects不能配置为false,需要将css文件加上,不然代码不生效,tree shaking 意思是引入的模块必须使用才会打包,css看不出来使用,只引入,所以需要将css忽略

"sideEffects": [
    "*.css"
  ],

 总结:webpack.dev.js使用style-loader,webpack.prod.js使用MiniCssExtractPlugin.loader 代替,这个loader不支持热更新(hmr),开发时会耗时,所以开发环境不配置,生产环境配置

posted on 2020-11-10 10:33  随心的博客  阅读(956)  评论(0编辑  收藏  举报