• webpack配置css代码分割和css压缩


    开始,按照我的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),开发时会耗时,所以开发环境不配置,生产环境配置

  • 相关阅读:
    葡萄城报表介绍:数据报表的七个原则
    while(scanf("%d",&n)!=EOF)
    不容易系列之(3)—— LELE的RPG难题
    错排公式
    _​_​i​n​t​6​4​ ​与​l​o​n​g​ ​l​o​n​g​ ​i​n​t
    杭电ACM 2046 阿牛的EOF牛肉串
    C++Builder 中使用 __int64 整数的问题
    折线分平面——杭电2050
    复合梯形公式与复合辛普森公式求积分
    两套蓝桥杯热身题
  • 原文地址:https://www.cnblogs.com/uimeigui/p/13952526.html
Copyright © 2020-2023  润新知