在React中使用.less文件 [英] Using .less files with React

查看:31
本文介绍了在React中使用.less文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将.less文件用于极简的React应用程序(通过 create-react-app 创建).我在 package.json 中添加了 less less-loader 以及 webpack.config中的模块规则.js 文件.但是,该类引用未添加到HTML元素中(应该具有 class ="customColor" ).

I am trying to use .less files with a minimalist React app (created with create-react-app). I've added less and less-loader to my package.json as well as a module rule in my webpack.config.js file. The class reference is not being added to the HTML element however (should have class="customColor").

<p>Hello world in a custom color.</p>

我想知道我在做错什么.

I'm wondering what I'm doing wrong.

import React from 'react';
import './App.css';
import styles from './custom.less';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <p className={styles.customColor}>
          Hello world in a custom color.
        </p>
      </header>
    </div>
  );
}

export default App;

custom.less

@custom-color: red;

.customColor {
  color: @custom-color;
}

package.json

{
  "name": "sample",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.9.0",
    "react-dom": "^16.9.0",
    "react-scripts": "3.1.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "devDependencies": {
    "less": "^3.10.3",
    "less-loader": "^5.0.0"
  }
}

webpack.config.js

module.exports = {
    rules: [{
        test: /\.less$/,
        use: [{
            loader: 'style-loader',
        }, {
            loader: 'css-loader', // translates CSS into CommonJS
        }, {
            loader: 'less-loader', // compiles Less to CSS
        }],
    }],
}

推荐答案

默认情况下,CRA(创建React应用)仅支持 SASS CSS code> LESS ,您需要先执行 npm run exit ,然后修改 webpack 配置.

CRA (Create React App) by default supports only SASS and CSS if you want to use LESS you need to do npm run eject first and then modify webpack configs.

但是有一种方法可以不弹出,我不得不说我个人更喜欢弹出.您可以在此处

However there is a way to do that w/o ejecting tho I have to say I personally prefer ejecting. You can find instructions here

这篇关于在React中使用.less文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆