react 的项目中使用less

React 的项目中使用less

react本身只支持sass,并不支持less所以安装less之前,必须修改 webpack.config.js 文件

  1. 必须要先执行 yarn eject 或者 npm run eject注意此操作是不可逆的
  2. 找到项目文件下的 config 文件夹中的 webpack.config.js 进行下一步的修改
  3. 进入 webpack.config.js 文件中,找到第42行,在后面添加以下代码
const lessRegex = /\.(less)$/;
const lessModuleRegex = /\.module\.(less)$/;
  1. 继续往下找到第446行在后面添加以下代码
			{
              test: cssModuleRegex,
              use: getStyleLoaders({
                importLoaders: 1,
                sourceMap: isEnvProduction && shouldUseSourceMap,
                modules: {
                  getLocalIdent: getCSSModuleLocalIdent,
                },
              }),
            },
            {
              test: lessRegex,
              exclude: lessModuleRegex,
              use: getStyleLoaders({ importLoaders: 3 }, "less-loader"),
            },
            {
              test: lessModuleRegex,
              use: getStyleLoaders(
                {
                  importLoaders: 3,
                  modules: true,
                  getLocalIdent: getCSSModuleLocalIdent,
                  modifyVars: {
                    "primary-color": "#1DA57A",
                    "link-color": "#1DA57A",
                    "border-radius-base": "2px",
                  },
                  javascriptEnabled: true,
                },
                "less-loader"
              ),
            },
  1. 安装 less 以及 less-loader ,运行下面代码
yarn add less less-loader --save 

或者

npm install less less-loader --save
  1. 运行项目,使用 yarn start 或者 npm start
  2. 此时我遇到一个错误:错误提示是缺少一个 @babel/helper-create-regexp-features-plugin (由于报错之后没有来得及截图,此处无项目报错信息截图),我便按照提示执行了 yarn add @babel/helper-create-regexp-features-plugin -D 或者 npm install @babel/helper-create-regexp-features-plugin -D 命令,按照了此插件。
  3. 随后我又执行 yarn start 或者 npm start ,启动项目。
  4. 再次出现以下报错
    在这里插入图片描述
    错误提示为:找不到 @babel/plugin-syntax-jsx 这个插件,随后便执行了 yarn add @babel/plugin-syntax-jsx -D 或者 npm install @babel/plugin-syntax-jsx -D 按照插件。
  5. 执行了 yarn start 或者 npm start 运行项目。项目成功启动。
  6. 测试是否成功,在项目文件下的 src 文件夹内新建 index.less 的 less 文件 在这里插入图片描述
  7. 在 index.less 文件内写入以下代码
@bgc: #1296db;

html,body {
  background-color: @bgc;
}
  1. 打开同目录 src 下的 index.js 文件中,在顶部添加一行 import './index.less';
    在这里插入图片描述

  2. 修改 App.js 文件
    在这里插入图片描述

  3. 成功运行项目,打开浏览器,出现以下画面
    在这里插入图片描述

本人首次写博客,若有不当之处,请留言提示!谢谢支持

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值