Published: February 10 2020

React - How to add Global CSS / LESS styles to React with webpack

The below steps show how to quickly add a global LESS / CSS stylesheet to your React application using Webpack.


Install LESS / CSS webpack loaders into your React project

Run the following command from the root folder of your React project to install the npm packages required to convert LESS styles into CSS, then load the CSS styles and inject them into the DOM.

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


Create global LESS / CSS stylesheet for your React app

Create a LESS stylesheet named styles.less (the name can be anything you like) in the /src folder of your React project with some simple styles for testing, for example:

body {
    background-color: #1abc9c;
}


Add module rules to your React webpack config

Update your React webpack.config with the following module rules so webpack knows how to process *.less files.

{
    test: /\.less$/,
    use: [
        { loader: 'style-loader' },
        { loader: 'css-loader' },
        { loader: 'less-loader' }
    ]
}


Here's a complete example React webpack config file with the LESS / CSS rules included.

var HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');

module.exports = {
    mode: 'development',
    module: {
        rules: [
            {
                test: /\.jsx?$/,
                loader: 'babel-loader'
            },
            {
                test: /\.less$/,
                use: [
                    { loader: 'style-loader' },
                    { loader: 'css-loader' },
                    { loader: 'less-loader' }
                ]
            }
        ]
    },
    resolve: {
        extensions: ['.js', '.jsx'],
        alias: {
            '@': path.resolve(__dirname, 'src/'),
        }
    },
    plugins: [new HtmlWebpackPlugin({
        template: './src/index.html'
    })],
    devServer: {
        historyApiFallback: true
    },
    externals: {
        // global app config object
        config: JSON.stringify({
            apiUrl: 'http://localhost:4000'
        })
    }
}


Import global LESS / CSS stylesheet into main React entry file

Import the styles.less global stylesheet into your main React entry file (e.g. /src/index.js or /src/index.jsx) with the following line.

import './styles.less';


Here's an example main React entry file that includes the imported global styles.

import React from 'react';
import { render } from 'react-dom';

import { App } from './App';

import './styles.less';

render(
    <App />,
    document.getElementById('app')
);

 


Need Some React Help?

Search fiverr for freelance React developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by