Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import global variables in less-loader

Tags:

In my webpack config, I want to be able to define a global less-variables file which would be included in every less component.

With the sass-loader you can supply the following option:

loaderOptions: {
    data: "@import 'globals.sass'"
}

The only option I could find with the less-loader is globalVars:

loaderOptions: {
    globalVars: {}
}

Now, this works all right, but globalVars expects an object with key-value pair. I'd rather have a theme.less somewhere which is appended with every component. Is this possible with the less-loader?

like image 485
Rinux Avatar asked Aug 29 '18 10:08

Rinux


1 Answers

I suggest chaining your less-loader with the text-transform-loader, like this:

rules: [{
     test: /\.js$/,
     use: [
         { 
            loader: 'less-loader',
            options: //your normal options
         },
         { 
            loader: 'text-transform-loader',
            options: {
               prependText: '@import "../styles/theme.less"'
            }
         }
     ]
}]

Remember that the last webpack loader is applied first, so you probably want to use this one as the last loader in your chain. This may well break if your less files are nested at different depths, because then your theme file will be at different depths relative to each one. If that's the case, you could just append the entire content of the theme file to each less file!

Would also be a good idea to exclude your theme.less file from this rule, otherwise you could get some weird infinite recursion.

See https://github.com/kmck/webpack-text-transform-loader for details.

like image 81
Duncan Thacker Avatar answered Sep 28 '22 19:09

Duncan Thacker