React官方脚手架不支持less问题解决

create-react-app是由React官方提供,并推荐构建React单页应用程序的最佳方法,但是默认不支持less,需要手动集成:

1,必须手动安装less

npm install less less-loader

2,暴露webpack配置文件【npm run eject】,修改weppack.config.js文件中,添加less配置

在module.rules节点中找到 css 文件的加载规则:

  1. test: /\.css$/ 修改为 test: /\.(css|less)$/
  2. use数组最后新增一个对象元素{loader: require.resolve('less-loader')}

修改完成后:

const getStyleLoaders = (cssOptions, preProcessor) => {
    const loaders = [
      isEnvDevelopment && require.resolve('style-loader'),
      isEnvProduction && {
        loader: MiniCssExtractPlugin.loader,
        options: Object.assign(
          {},
          shouldUseRelativeAssetPaths ? { publicPath: '../../' } : undefined
        ),
      },
      {
        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,
            }),
          ],
          sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
        },        
      },
      {
        loader: require.resolve('less-loader') // compiles Less to CSS
      }
    ].filter(Boolean);
    if (preProcessor) {
      loaders.push({
        loader: require.resolve(preProcessor),
        options: {
          sourceMap: isEnvProduction ? shouldUseSourceMap : isEnvDevelopment,
        },
      });
    }
    return loaders;
  };

需要重新启动项目,即可看到less样式可用!

 

【完】

新年flag3——每个月读两本书,微信读书打卡或者宅机kindle打卡

 

posted @ 2019-02-12 17:46  tangjiao_Miya  阅读(710)  评论(0编辑  收藏  举报