6

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?

Rinux
  • 815
  • 1
  • 9
  • 18

3 Answers3

4

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.

Duncan Thacker
  • 5,073
  • 1
  • 10
  • 20
1

There are two ways to do that under less options:

  1. additionalData
additionalData: (content, loaderContext) => {
     return `@import '~@/global.less';${content}`
}
  1. lessOptions
lessOptions: {
     modifyVars: {
          // you should config resolve alias option for @
          [any key name you like]: `true;@import'~@/global.less';`,
     },
}

They are the same results and principles, except additionalData can prepend or append, while modifyVars can only append. More details can be found in less-loader source code.

darkmnemic
  • 272
  • 3
  • 13
Peter Yu
  • 27
  • 2
0

That is the way I do:

rules: [{
    test: /\.less$/,
    use: [{
        loader: 'less-loader',
        options: {
            javascriptEnabled: true
        }
    },
        {
            loader: 'style-resources-loader',
            options: {
                patterns: [
                    path.resolve(__dirname, 'src/application/less/variables.less'),
                    path.resolve(__dirname, 'src/application/less/flex.less'),
                    path.resolve(__dirname, 'src/application/less/functions.less'),
                ]
            }
        }]
}]
IsraGab
  • 4,819
  • 3
  • 27
  • 46