webpack css模块化和ant-design按需加载冲突

其实具体出现了什么问题,我也记得不清楚了,今天突然回想起来必须记录一下,一个思想就是用exclude将node_module目录下的文件排除,网上有很多相关例子,但不知是不是因为时间久远,都不生效,无奈,又只好啃回官方文档,我的解决方式如下

webpack正常打包的话,所有的css都会被打包在一起,造成css的全局污染,我们可以采用模块化的方式,其实就是借用hash改变类或id名
webpack.config.js

  module: {
    rules: [     
 {
        test: /.(js|jsx)$/,
        loader: "babel-loader",

        options: {
          // presets: [
          //           //   "env"
          //           // ],
          plugins: [
              [ "import",{libraryName: "antd", style: 'css'}] // antd按需加载
          ]
        },

        exclude: /node_module/
      },
      {//CSS处理
        test: /.css$/,
        use: ['style-loader', 'css-loader?modules'],
        exclude: /node_modules/,
      },

      {//antd样式处理
        test:/.css$/,
        exclude:/src/,
        use:[
          { loader: "style-loader",},
          {
            loader: "css-loader",
            options:{
              importLoaders:1
            }
          }
        ]
      },
//其他配置项
       }
    ]

然后在js文件中我们就能模块化加载css而不用担心webpack打包后污染到全局啦

形如

import styles from './myTrip.css';

然后还可以快乐加载ant-design

import { Pagination } from 'antd';
原文地址:https://www.cnblogs.com/yuyuan-bb/p/11478882.html