美文网首页
React添加less

React添加less

作者: 板栗炖牛肉 | 来源:发表于2020-11-12 15:19 被阅读0次

    前言

    参考过很多create-react-app生成项目添加less,但是总有些问题。最后仿照css搞了一份,但是每次建新项目都会忘记,所以做个记录

    解决方案

    1.安装(使用yarn或者npm都行)

    less@3.12.2
    less-loader@7.1.0
    

    2.找到文件(忘记了需不需要eject,没有就执行npm run eject)

    webpack.config.js
    

    3.找到css顶部配置

    const cssRegex = /\.css$/;
    const cssModuleRegex = /\.module\.css$/;
    const sassRegex = /\.(scss|sass)$/;
    const sassModuleRegex = /\.module\.(scss|sass)$/;
    //仿造css写的
    const lessRegex = /\.less$/;
    const lessModuleRegex = /\.module\.less$/;
    

    4.找到css底部代码(ctrl+f往下找cssModuleRegex)

                    {
                                test: cssRegex,
                                exclude: cssModuleRegex,
                                use: getStyleLoaders({
                                    importLoaders: 1,
                                    sourceMap: isEnvProduction && shouldUseSourceMap,
                                }),
                                // Don't consider CSS imports dead code even if the
                                // containing package claims to have no side effects.
                                // Remove this when webpack adds a warning or an error for this.
                                // See https://github.com/webpack/webpack/issues/6571
                                sideEffects: true,
                            },
                            // Adds support for CSS Modules (https://github.com/css-modules/css-modules)
                            // using the extension .module.css
                            {
                                test: cssModuleRegex,
                                use: getStyleLoaders({
                                    importLoaders: 1,
                                    sourceMap: isEnvProduction && shouldUseSourceMap,
                                    modules: {
                                        getLocalIdent: getCSSModuleLocalIdent,
                                    },
                                }),
                            },
    

    5.css的配置是上面的,仿照写(写的位置也要相同)

           {
                                test: lessRegex,
                                exclude: lessModuleRegex,
                                use: getStyleLoaders(
                                    {
                                        importLoaders: 3,
                                        sourceMap: isEnvProduction && shouldUseSourceMap,
                                    },
                                    'less-loader'
                                ),
                                sideEffects: true,
                            },
                            {
                                test: lessModuleRegex,
                                use: getStyleLoaders(
                                    {
                                        importLoaders: 3,
                                        sourceMap: isEnvProduction && shouldUseSourceMap,
                                        modules: {
                                            getLocalIdent: getCSSModuleLocalIdent,
                                        },
                                    },
                                    'less-loader'
                                ),
                            },
    

    6.项目重启,试试less导入和less module的导入

    //module命名规则
    xxx.module.less
    
    //导入
    import less from './xxx.module.less'
    
    //使用
    className={less.xxx}
    

    加入javascriptEnabled(非需要,请略过)

    • 某些需求需要开启Less的javascriptEnabled,比如接入ant landing时。

    1.在解决方案的基础上。我们在webpack里配置了如下

         {
                                test: lessRegex,
                                exclude: lessModuleRegex,
                                use: getStyleLoaders(
                                    {
                                        importLoaders: 3,
                                        sourceMap: isEnvProduction && shouldUseSourceMap,
                                    },
                                    'less-loader'
                                ),
                                sideEffects: true,
                            },
                            {
                                test: lessModuleRegex,
                                use: getStyleLoaders(
                                    {
                                        importLoaders: 3,
                                        sourceMap: isEnvProduction && shouldUseSourceMap,
                                        modules: {
                                            getLocalIdent: getCSSModuleLocalIdent,
                                        },
                                    },
                                    'less-loader'
                                ),
                            },
    

    2.现在我们需要开始javascriptEnabled,找到如下函数

    getStyleLoaders
    

    3.其完整函数

      const getStyleLoaders = (cssOptions, preProcessor) => {
        const loaders = [
          isEnvDevelopment && require.resolve('style-loader'),
          isEnvProduction && {
            loader: MiniCssExtractPlugin.loader,
            // css is located in `static/css`, use '../../' to locate index.html folder
            // in production `paths.publicUrlOrPath` can be a relative path
            options: paths.publicUrlOrPath.startsWith('.')
              ? { publicPath: '../../' }
              : {},
          },
          {
            loader: require.resolve('css-loader'),
            options: cssOptions,
          },
          {
            // Options for PostCSS as we reference these options twice
            // Adds vendor prefixing based on your specified browser support in
            // package.json
            loader: require.resolve('postcss-loader'),
            options: {
              // Necessary for external CSS imports to work
              // https://github.com/facebook/create-react-app/issues/2677
              ident: 'postcss',
              plugins: () => [
                require('postcss-flexbugs-fixes'),
                require('postcss-preset-env')({
                  autoprefixer: {
                    flexbox: 'no-2009',
                  },
                  stage: 3,
                }),
                // Adds PostCSS Normalize as the reset css with default options,
                // so that it honors browserslist config in package.json
                // which in turn let's users customize the target behavior as per their needs.
                postcssNormalize(),
              ],
              sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
            },
          },
        ].filter(Boolean);
        if (preProcessor) {
          loaders.push(
            {
              loader: require.resolve('resolve-url-loader'),
              options: {
                sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
                root: paths.appSrc,
              },
            },
            {
              loader: require.resolve(preProcessor),
              options: {
                sourceMap: true,
              },
            }
          );
        }
        return loaders;
      };
    

    4.在函数下方拷贝如下

      const getStyleLessLoaders = (cssOptions, lessOptions) => {
        const loaders = [
          isEnvDevelopment && require.resolve('style-loader'),
          isEnvProduction && {
            loader: MiniCssExtractPlugin.loader,
            // css is located in `static/css`, use '../../' to locate index.html folder
            // in production `paths.publicUrlOrPath` can be a relative path
            options: paths.publicUrlOrPath.startsWith('.')
                ? { publicPath: '../../' }
                : {},
          },
          {
            loader: require.resolve('css-loader'),
            options: cssOptions,
          },
          {
            // Options for PostCSS as we reference these options twice
            // Adds vendor prefixing based on your specified browser support in
            // package.json
            loader: require.resolve('postcss-loader'),
            options: {
              // Necessary for external CSS imports to work
              // https://github.com/facebook/create-react-app/issues/2677
              ident: 'postcss',
              plugins: () => [
                require('postcss-flexbugs-fixes'),
                require('postcss-preset-env')({
                  autoprefixer: {
                    flexbox: 'no-2009',
                  },
                  stage: 3,
                }),
                // Adds PostCSS Normalize as the reset css with default options,
                // so that it honors browserslist config in package.json
                // which in turn let's users customize the target behavior as per their needs.
                postcssNormalize(),
              ],
              sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
            },
          },
        ].filter(Boolean);
        if (lessOptions) {
          loaders.push(
              {
                loader: require.resolve('resolve-url-loader'),
                options: {
                  sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
                  root: paths.appSrc,
                },
              },
              {
                loader: require.resolve('less-loader'),
                options: {
                  sourceMap: true,
                  lessOptions: {
                    ...lessOptions
                  }
                },
              }
          );
        }
        return loaders;
      };
    

    5.主要变更如下

            {
                loader: require.resolve('less-loader'),
                options: {
                  sourceMap: true,
                  lessOptions: {
                    ...lessOptions
                  }
                },
              }
    

    6.修改第一步less配置

       {
                  test: lessRegex,
                  exclude: lessModuleRegex,
                  use: getStyleLessLoaders(
                      {
                        importLoaders: 3,
                        sourceMap: isEnvProduction && shouldUseSourceMap,
                      },
                      {
                        javascriptEnabled: true   //开启 
                      }
                  ),
                  sideEffects: true,
                },
                {
                  test: lessModuleRegex,
                  use: getStyleLoaders(
                      {
                        importLoaders: 3,
                        sourceMap: isEnvProduction && shouldUseSourceMap,
                        modules: {
                          getLocalIdent: getCSSModuleLocalIdent,
                        },
                      },
                      'less-loader'
                  ),
                },
    

    Ps

    • 当前更新 2021-2-19 less版本过高 CRA用当前方法会报错(等待CRA的webpack配置更新)
    TypeError: this.getOptions is not a function
    

    目前解决方法,降版本,开始有版本号

    • javascriptEnabled使用注意版本,低版本将
     options: {
                  sourceMap: true,
                  lessOptions: {
                    ...lessOptions
                  }
    

    改为

     options: {
                  sourceMap: true,
               ...lessOptions
                 }
    

    相关文章

      网友评论

          本文标题:React添加less

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