create-react-app 支持less踩坑

  • 通过create-react-app 是默认不支持less的,所以需要自己配置
  • 编译成功有className在项目中显示为undefined

打开配置

 npm run eject

在项目文件根目录下可以看到config文件夹,打开其中的webpack.config.js

配置

// style files regexes
const cssRegex = /\.css\$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;

在下面加上我们的less配置

// style files regexes
const cssRegex = /\.css\$/;
const cssModuleRegex = /\.module\.css$/;
const sassRegex = /\.(scss|sass)$/;
const sassModuleRegex = /\.module\.(scss|sass)$/;
const lessRegex = /\.(less)$/;
const lessModuleRegex = /\.module\.(less)$/;

找到文件中cssRegexsassRegex的配置项,在同级加上以下内容即可

 // Less 解析配置
  {
    test: lessRegex,
    exclude: lessModuleRegex,
    use: getStyleLoaders(
      {
        importLoaders: 2,
        sourceMap: isEnvProduction && shouldUseSourceMap,
        modules: true
      },
      "less-loader"
    ),
    sideEffects: true,
  },
   {
      test: lessModuleRegex,
      use: getStyleLoaders(
        {
          importLoaders: 2,
          sourceMap: isEnvProduction && shouldUseSourceMap,
          modules: true,
          getLocalIdent: getCSSModuleLocalIdent,
        },
        "less-loader"
      ),
    },
注意⚠️

如果你看了其他的配置方法,在代码配置规则中加入了以上内容,在运行时发现导入成功,但是className在项目中显示为undefined请加上以下两项中的一项。

modules: {
          getLocalIdent: getCSSModuleLocalIdent,
        },

modules: true,

这项加上之后,在less文件编译之后,被引用的地方className会保留自己设置的className并拼接上hash值。如下:
在这里插入图片描述
如果不加这项配置的话,打包出来的资源className自己也看不懂,不方便开发。

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值