美文网首页
webpack5+mini-css-extract-plugin

webpack5+mini-css-extract-plugin

作者: 野小宝 | 来源:发表于2023-02-19 15:23 被阅读0次

    Question:

    webpack5打包不能提取css为单独的文件(mini-css-extract-plugin)

    Desc

    webpack中配置了mini-css-extract-plugin用来提取样式到独立文件,可运行启动时,却没有生成css文件,页面没有样式。
    技术栈:react+webpack5
    配置如下:

    const path = require('path');
    const HtmlWebpackPlugin = require('html-webpack-plugin');
    const MiniCssExtractPlugin = require('mini-css-extract-plugin');//提取css文件
    const ESLintPlugin = require('eslint-webpack-plugin');
    const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
    
    module.exports= {
      module:{
        rules:[
          {
            test:/\.less$/,
            use:[
              MiniCssExtractPlugin.loader,//提取css成单独文件
               {
                loader: 'css-loader',
                options: {
                  modules: {
                    getLocalIdent: (context, localIdentName, localName) => {
                      return localIdentName;
                    },
                  }
                },
              },
              'postcss-loader',//css兼容
              'less-loader'
            ],
          }
        ]
      },
      plugins:[
        new ESLintPlugin({
          context:path.resolve(__dirname,'../src'),//绝对路径,配置需要检查的文件
          exclude:"node_modules",//排除node_modules下的文件,
          cache:true,//开启缓存
          cacheLocation:path.resolve(__dirname,'../node_modules/eslintcache')//配置缓存文件地址,同样配到node_modules下面
        }),
        new HtmlWebpackPlugin({
          template:path.resolve(__dirname,'../src/index.html'),//绝对路径
          title:'纯手工打造一款react应用'
        }),
        new MiniCssExtractPlugin({filename:'[name].[contenthash:8].css'}),
        new ReactRefreshWebpackPlugin()//js热更新
      ],
      devServer:{
        compress: true,
        port: 8081,
        hot:true,
        historyApiFallback: true,
        proxy: {
          '/api': 'http://192.168.1.2:8000/api/drf_stock/',
        },
      }
    }
    

    Answer:

    排查后发现是package.json中配置了sideEffects:false导致css被当作无副作用的静态资源,被删除掉了。
    sideEffects副作用:webpack4的一个新功能,允许通过配置的方式去标识代码是否有副作用,从而为 Tree Shaking 提供更多的压缩空间,sideEffects 一般用于开发npm模块时,标记是否有副作用。官方文档中将它和 Tree Shaking 放在一起讲,所以容易误解为它们是因果关系,实际上二者没什么关系。

    image.png

    方案一:直接删掉package.json中的sideEffects属性配置
    方案二:将css文件添加到 sideEffect 列表中,以免在生产模式中无意中将它删除

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

    拓展

    Tree Sharking & sideEffects 副作用
    1. sideEffects 副作用(副作用:模块执行时除了导出成员之外所作的事情),一般用于开发npm模块(import,export)时,标记是否有副作用
    2. Tree Sharking树摇,二者不是因果关系
    3. sideEffects 允许通过在配置的方式去标识代码是否有副作用,从而为 Tree Shaking 提供更多的压缩空间。
    package.json和webpack配置文件中的sideEffects的区别
    1. package.json的sideEffects:标识当前package.json所影响的项目,当中所有的代码是否有副作用,默认true,表示当前项目中的代码有副作用

    2. webpack配置文件中的sideEffects:开启功能,是否移除无副作用的代码
      默认false,表示不移除无副作用的模块。在production模式下自动开启。
      webpack只能通过读取package.json的sideEffects字段来识别代码是否有副作用

    3. 二者需要配合使用,才能处理无副作用的模块。

    sideEffects 使用注意

    使用webpack sideEffects功能的前提是,确保代码没有副作用。
    否则webpack打包时就会误删那些有副作用的代码。
    例如导入一个模块,它的内容是立即执行的,而不是通过导出成员等待被调用。

    //onload.js绑定初始事件
    window.onload=()=>{
    //do something
    }
    //index.js
    import './onload.js'
    

    解决办法 & 常用方案:

    1. 在package.json中关闭标识无副作用
    2. 或者具体标识项目中哪些文件有副作用,webpack就不会忽略这些有副作用的模块,这种方式,未被标识的模块,就会被当作无副作用处理
    //package.json
    // ...
    "sideEffects": [
      "**/*.css",
      "**/*.scss",
      "./esnext/index.js",
      "./esnext/configure.js"
    ],
    // ...
    

    相关文章

      网友评论

          本文标题:webpack5+mini-css-extract-plugin

          本文链接:https://www.haomeiwen.com/subject/jtiohdtx.html