tensdil
tensdil

Reputation: 41

LESS style not applied to react component in react+webpack application

In a react + web pack application, I'm trying to style my react component using LESS, but the style does not get applied, although I get no errors, so I wouldn't know where to look. Of course, my devDependencies includes less, less-loader, CSS-loader and style-loader.

webpack.config.js

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

module.exports = {
    entry: './src/index.js',
    module: {
        rules: [
             {
                test: /\.(js|jsx)$/,
                exclude: /node_modules/,
                use: [
                    "babel-loader",
                    "eslint-loader"
                ]
            },
            {
                test: /\.(c|le)ss$/,
                use: [
                    "style-loader",
                    "css-loader",
                    "less-loader",
                ]
            }
        ]
    },
    resolve: {
        extensions: [".js", ".jsx"],
        alias: {
            "@components": path.resolve(__dirname, "src/components"),
            "@containers": path.resolve(__dirname, "src/containers")
        }
    },
    output: {
        path: __dirname + '/dist',
        filename: 'bundle.js'
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin()
      ],
    devServer: {
        contentBase: './dist',
        hot: true
    }
};

components/App/App.jsx

import React from "react";
import Body from "@components/Body/Body.jsx";
import Footer from "@components/Footer/Footer.jsx";

import styles from "./App.less";

class App extends React.Component {

    render() {

        return <div className={styles.root}>
            <h1> test </h1>
            <Body />
            <Footer />
        </div>;
    }
}

export default App;

components/App/App.less

.root {
    width: 100%;
    height: 100%;
    background-color: coral;

    h1 {
        margin-top: 200px;
        color: red;
    }
}

I expected to see the style applied, but it's not.

Upvotes: 2

Views: 5428

Answers (2)

tensdil
tensdil

Reputation: 41

I had to enable CSS Modules in the Webpack config:

{
    test: /\.(c|le)ss$/,
    use: [
        "style-loader",
        {
            loader: 'css-loader',
            options: {
                modules: true,
                localIdentName: "[path][name]__[local]--[hash:base64:5]",
            },
        },
        "less-loader"
    ]
},

Upvotes: 2

Codekie
Codekie

Reputation: 7834

Try setting "root" as string-value to className.

The way your webpack has been configured, the content of the LESS-files will not be exported as css-rules but only collected to be rendered into a style-tag.

You need to import the less-file, so webpack knows which files to consider, but you neither can access its rules, or its styles. So to make it work, you simply set the CSS-class names so that the compiled CSS-rules match.

Upvotes: 2

Related Questions