create-react-app中安装并引用less

摘要

  1. 执行暴露出webpack 相关的配置文件
  2. 安装less
  3. 修改webpack配置
  4. less版本报错及兼容处理

具体步骤

1. 执行暴露出webpack 相关的配置文件

在使用了create-react-app my-app之后 ,使用 npm run eject 暴露出webpack 相关的配置文件

create-react-app my-app
cd my-app 
npm run eject 

2. 安装less

npm install less-loader less --save-dev

3. 修改webpack配置

你会发现是不是少了一个很重要的webpack.config.js文件呢?

官方文档提示:默认配置文件都是隐藏的,点开package.json文件,可看到配置的命令是以 “react-scripts *” 来执行。

所以打开node_modules文件夹,找到react-scripts文件夹进去, config目录即是你需要找的webpack的配置文件。

参考链接

3.1 找寻webpack.config.js目录

文件所在目录

3.2 配置 .less 文件 和 module 正则

在这里插入图片描述

const lessRegex = /\.less$/i;
const lessModuleRegex = /\.module\.less$/;
3.3 在 getStyleLoader中添加 less 配置

在 getStyleLoader中添加 less 配置

      {
        loader: require.resolve('less-loader'), 
        options: lessOptions,
      },
4. test 中进行 配置

找到这两个位置
在这里插入图片描述
在他们同级目录下 添加如下代码
在这里插入图片描述

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

然后重启项目

4.less版本报错及兼容处理

!>this.getOptions is not a function
less版本报错及兼容处理
原因: less-loader安装的版本过高
解决方案:

npm uninstall less-loader
npm install less-loader@5.0.0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值