React Series: Make create-react-app Support LESS Imports

Currently, create-react-app does not support importing LESS directly. Here I’ll show you how to make it support LESS imports.

create-react-app is based on webpack, but it doesn’t expose the webpack.config files. To support LESS, you need to modify the webpack configuration. The following command exposes the configuration files:

npm run eject

After running it, you’ll see a new config folder. Inside are files like webpack.config.dev.js and webpack.config.prod.js.

Next, install less-loader

npm install less-loader less --save-dev

Then modify the webpack.config.dev.js file.

We only need to modify two places:

First: Find the following code

exclude: [
    /\.html$/,
    /\.(js|jsx)$/,
    /\.css$/,
    /\.json$/,
    /\.bmp$/,
    /\.gif$/,
    /\.jpe?g$/,
    /\.png$/,
]

Change .css to .(css|less), making it:

exclude: [
    /\.html$/,
    /\.(js|jsx)$/,
    /\.(css|less)$/,
    /\.json$/,
    /\.bmp$/,
    /\.gif$/,
    /\.jpe?g$/,
    /\.png$/,
]

Second: Find test: /.css$/

Change it to test: /.(css|less)$/

And add less-loader in the use array below:

{
    loader: require.resolve('less-loader') // compiles Less to CSS
}

After modification, this part should look like this:


      {
        test: /\.(css|less)$/,
        use: [
          require.resolve('style-loader'),
          {
            loader: require.resolve('css-loader'),
            options: {
              importLoaders: 1,
            },
          },
          {
            loader: require.resolve('less-loader') // compiles Less to CSS
          }

          ...

        ],
      }

The production configuration is similar.


Now you can import LESS files:

import './style.less';

Article Link:

/en/archive/create-react-app-less/

# Related Articles