create-react-app 添加less-css-modules

  1. create-react-app demo
  2. npm run eject
  3. npm i less less-loader --save
  4. npm i less-watch-compiler --save-dev
  5. 在package.json 中添加

    "scripts":{ 
          "build-css": "less-watch-compiler --run-once --main-file=index.less src/less src/css",
           "watch-css": "npm run build-css && less-watch-compiler --main-file=index.less src/less src/css"
        }
  6. 运行npm run watch-css
  7. 在config 中的 webpack.config.js 中配置

    // 修改前
       {
         loader: require.resolve('css-loader'),
         options: cssOptions
       },
       // 修改后
       {
         loader: require.resolve('css-loader'),
         options: {
           importLoaders: 1,
           modules: true,
           localIdentName: "[name]__[local]___[hash:base64:5]"     // 更改css modules 生成方法
         },
       },
       // 修改webpack 配置less 部分, 按照sass 相同配置
        const lessRegex = /\.less$/
        const lessModuleRegex = /\.module\.less$/ 
        oneOf:[
               ...,
               {
                 test: lessRegex,
                 use: getStyleLoaders(
                   {
                     importLoaders: 2,
                     sourceMap: isEnvProduction
                       ? shouldUseSourceMap
                       : isEnvDevelopment,
                   },
                   'less-loader'
                 )
               },
               {
                 test: lessModuleRegex,
                 use: getStyleLoaders(
                   {
                     importLoaders: 2,
                     sourceMap: isEnvProduction
                       ? shouldUseSourceMap
                       : isEnvDevelopment,
                     modules: true,
                     getLocalIdent: getCSSModuleLocalIdent
                   },
                   'less-loader'
                 ),
                 sideEffects: true
               },
           ]

8.删除原有依赖 重新安装依赖, 然后npm start 运行即可

相关推荐