webpacklessless-loader

How can I use a common base path to import from with a generic less webpack setup?


I am using a web stack of typescript+react and less together with webpack.

My webpack ruleset for less files looks like the following:

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

I do have a bit of difficulties figuring out how to do some proper less importing now.

I created a file containing some common definitions, called "Colors.less". It resides in React/Common/Styles/Colors.less.

It's content for now:

@navy: #001f3f;

Now, I want to import this file from another file residing here: React/Modules/Chat/Styles/ChatWidgetTopBar.less.

Here is what I've tried:

@import (reference) "../../../../Common/Styles/Colors.less";

.ChatWidgetTopBar {
    height: 25px;
    width: 100%;

    background-color: @navy;

    cursor: pointer;
}

This also works just fine, however, is there also a possibility to set a common base path for less imports? So that I wouldn't have to do this relative ../../ etc.? I read that webpack allows you to combine variables e.g. @basepath = "mybasepath/folder" into something like @import "{basePath}/folder2, but how can I make that @basepath shared then?


Solution

  • You can make use of resolve.modules, Something like this:

    module.exports = {
        resolve: {
            modules: ['<youbasepath>']
        },
        ...
    }
    

    This way webpack will try to resolve your .less module from this path root.