Neko
Neko

Reputation: 589

How to use LESS in React 16.7 with webpack 4.29?

I am just start to learn React, and I want to use less in React. I did some research about it , and they said I should write the config in webpack.config.dev.js but , after I run npm run eject I only got one file :webpack.config.js .

I think maybe that's because the update , the new version maybe combined webpack.config.dev.js and webpack.config.prod.js to `webpack.config.js .

and I checked the homepage of webpack , it says:

// webpack.config.js
module.exports = {
  ...
  module: {
    rules: [{
      test: /\.js$/,
      issuer: /\.less$/,
      use: [{
        loader: 'js-to-less-loader'
      }]
    }]
  }
};

but I don't know where to insert these code. I did not find any code like that.so I want a simple example for how to support less in React.

Thanks.

Upvotes: 1

Views: 4447

Answers (2)

Priyesh Diukar
Priyesh Diukar

Reputation: 2142

I believe you are using the create-react-app starter kit. Well its good but if you want to add more features to your setup, Starter kits come with their own complications.

You can learn to setup react instead of letting the starter kit handling it for you.

Anyways you can try this,

You will need babel depedencies for handling transpilation:

npm install babel-core babel-loader babel-preset-env babel-preset-react --save-dev

Setup your react dependencies like so:

npm i react react-dom --save-dev

Once you are done with this setup, include your .bablerc file with the following code:

{
  "presets" : [
    "env",
    "react"
  ]
}

Setup dependencies to load your css/less files. This will fetch all the loaders you require for css and less.

npm install less less-loader style-loader css-loader --save--dev

Now you will need an HTML plugin and a template .html file for webpack to serve your react.

npm i html-webpack-plugin html-loader --save-dev

The template file (save this as src/index.html):

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title><%= htmlWebpackPlugin.options.title %></title>
</head>
<style>
    * {
        box-sizing: border-box;
    }
</style>
<body>
    <div class='content' id='app'></div>
</body>
</html>

You will now need a webpack devServer for serving the generated index.html

npm install webpack-dev-server --save-dev

Add the following to your package.json file

"scripts": {
  "start": "webpack --mode development",
  "build": "webpack --mode production"
}

By now you should be having a webpack.config.js file, which fairly looks like this.

const path = require('path');
const webpack = require('webpack');

const HtmlWebPackPlugin = require("html-webpack-plugin");

module.exports = (env, argv) => {
    const {
        mode
    } = argv;
    return {
        module: {
            entry: path.join(__dirname, 'src', 'app.js'),
            watch: mode !== 'production',
            output: {
                path: path.join(__dirname, 'dist'),
                filename: mode === 'production' ? 'bundle.min.js' : 'bundle.js'
            },
            rules: [{
                test: /\.js$/,
                exclude: /node_modules/,
                use: ['babel-loader']
            },
            {
                test: /\.less$/,
                use: ['style-loader', 'css-loader', 'less-loader']
            }
            ],
            plugins: [
                new HtmlWebPackPlugin({
                    title: 'App',
                    template: "./src/index.html",
                    filename: "./index.html"
                })
            ]
        },
        devServer: {
            contentBase: path.join(__dirname, 'dist')
        }
    };
}

And a app.js file in your src folder like so,

import React from 'react';
import ReactDOM from 'react-dom';
import './styles/style.less'

ReactDOM.render( <div> Hello from react! </div>, document.getElementById("app"));

Use npm start to run the dev version.

Hope this helps. Let me know if you face any issues. I agree this is tedious work for the first time. But it does help in the long run to scale with features.

Upvotes: 1

Sumanth Madishetty
Sumanth Madishetty

Reputation: 3605

You need to do the following steps after ejecting to use less in react

1. Go to webpack.config.js file and search for cssRegex change it from /\.css$/ to /\.(?:le|c)ss$/
2. install less and less loader using npm install -S less less-loader
3. search for getStyleLoaders method in webpack config file and add the following object to array of loaders specified over there
    {
     loader: require.resolve('less-loader'),
     options: {
      importLoaders: 1,
     },
    }

Then you will be good to go, feel free to ask for clarifications if any

Upvotes: 2

Related Questions