How to use LESS preprocessor in React Create-React-APP

Viewed 13955

I want to use LESS preprocessor in my create-react-app.

React Code
ReactDOM.render(
    <form>
        <input type="email" data-info="Enter Email" pattern="/\S+@\S+\.\S+/" required title="Please enter value" required="required"/>
        <input type="submit"/>      
    </form>
    ,document.getElementById('root'))

index.less

body{
  background: red;
}
4 Answers

With create-react-app 2 you can use "Create React App Configuration Override" (craco) and craco-less to configure this:

set up craco:

npm install @craco/craco

in package.json:

  "scripts": {
    "start": "craco start",
    "build": "craco build",
    "test": "craco test",
    "eject": "craco eject"
  },

setting up craco for less:

npm install craco-less

create new file: craco.config.js

module.exports = {
  plugins: [
    {
      plugin: require('craco-less'),
    },
  ],
};

The simplest and painless way to add less support with reactjs app by far is to use custom-react-scripts with create-react-app for LESS/SASS/decorators support :

Install: npm install -g create-react-app custom-react-scripts

Create app: create-react-app <app_name> —scripts-version custom-react-scripts

Example less file:

.myDiv{ background: gray; }

and then in your component:

import lessStyles from '<less file path>';

<div style={lessStyles.myDiv}>
  ...
</div>

or the regular way:

import '<less file path>';

<div className="myDiv">
  ...
</div>

For reference:

https://github.com/kitze/custom-react-scripts

https://github.com/fawaz-ahmed/fawaz-ahmed.github.io

I've had a similar problem. Just include the following lines into your webpack configuration rules section (taken from the official less loader examples):

  {
    test: /\.less$/,
    use: [{
      loader: 'style-loader' // creates style nodes from JS strings
    }, {
      loader: 'css-loader' // translates CSS into CommonJS
    }, {
      loader: 'less-loader' // compiles Less to CSS
    }]
  },

Of course, you need to add respective packages into your package.json

And then in you code simply import needed styles

import './style.less'

Using such approach you won't introduce an extra step of creating additional css files.

Related