This article focuses on how to introduce LESS in React. Because less is very similar to CSS, it is easy to learn. And less adds only a few convenient extensions to the CSS language, which is one of the reasons less is so easy to learn.

1. Install less

npm install less less-loader --save-dev
Copy the code

2. Expose webpack files

The React project built with NPX creation-React-app hides the Webpack configuration file by default. Introducing less requires modifying the Webpack configuration file, so we need to run commands to expose the Webpack configuration file.

The important thing to note here is that once exposed, there is no fallback.

npm run eject
Copy the code

If this step fails, execute the following command:

git add .

git commit -m "init"
Copy the code

Then run NPM run eject

3. Modify the wenpack.config.js configuration

Add:

/ / in
// const sassRegex = /\.(scss|sass)$/;
// const sassModuleRegex = /\.module\.(scss|sass)$/; 
/ / behind

const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
Copy the code
// Put it in the oneof array

{
  test: lessRegex,
  exclude: lessModuleRegex,
  use: getStyleLoaders(
    {
      importLoaders: 2.sourceMap: isEnvProduction && shouldUseSourceMap,
    },
    'less-loader'
  ),
  // Don't consider CSS imports dead code even if the
  // containing package claims to have no side effects.
  // Remove this when webpack adds a warning or an error for this.
  // See https://github.com/webpack/webpack/issues/6571
  sideEffects: true,},// Adds support for CSS Modules, but using SASS
// using the extension .module.scss or .module.sass
{
  test: lessModuleRegex,
  use: getStyleLoaders(
    {
      importLoaders: 2.sourceMap: isEnvProduction && shouldUseSourceMap,
      modules: true.getLocalIdent: getCSSModuleLocalIdent,
    },
    'less-loader'),},Copy the code

4. How to use less

Create a new app.less file and introduce it in app.js:

import './Map.less'
Copy the code

Less Grammar Manual

This article link: shuxhan.com/post/26 welcome any form of reprint, but please be sure to indicate the source. Because the author level is limited, if the article or code is expressed improperly, please also give advice.