zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

How to import less in React?

This article mainly explains how to import less in React. Because less is very similar to CSS, it is easy to learn. In addition, less only adds a few convenient extensions to the CSS language, which is one of the reasons why less is so easy to learn.

1. Install less#

npm install less less-loader --save-dev

2. Expose the webpack file#

By default, the webpack configuration file is hidden when using npx create-react-app to set up a React project. To import less, we need to modify the webpack configuration file, so we need to execute the command to expose the webpack configuration file.

Note: Once exposed, there is no way to revert back.

npm run eject

If this step fails, execute the following commands:

git add .

git commit -m "init"

Then execute npm run eject again.

Note: Exposing the webpack file can only be done at the beginning of using create-react-app. Once the project structure changes, the exposure operation will fail. Therefore, it is recommended to perform the npm run eject operation when the project is established.

3. Modify the webpack.config.js configuration#

Add the following code at the appropriate location:

// Add after
// const sassRegex = /\.(scss|sass)$/;
// const sassModuleRegex = /\.module\.(scss|sass)$/; 

const lessRegex = /\.less$/;
const lessModuleRegex = /\.module\.less$/;
// Add under 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'
  ),
},

4. How to use less#

Create a new App.less file and then import it in App.js:

import './Map.less'

less syntax manual

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.