Importing Less from a JavaScript file into a Less file

691 Views Asked by At

I'm trying to import less generated through another loader from a JavaScript file.

Based on less-loaders README.md it should be possible:

Using webpack's resolver, you can import any file type. You just need a loader that exports valid Less code. Often, you will also want to set the issuer condition to ensure that this rule is only applied on imports originating from Less files.

But apparently it is not working. The less file always ends up with the JavaScript source, no matter which loaders I use. I also tried it with and without the recommended issuer condition, but to no avail. The custom loader I wrote to check if it is working is also not being called.


I'm using [email protected] with [email protected].

// ./webpack.config.js
{
    entry: './index.js',
    mode: 'development',
    module: {
        rules: [
            {
                test: /\.less$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'less-loader'
                ]
            },
            {
                test: /\.less\.js$/,
                issuer: /\.less$/, // <------
                use: [
                    {
                        loader: require.resolve('./test-loader.js')
                    }
                ]
            }
        ]
    }
}
// ./main.less
@import './import.less.js';

body { background: green; }
// ./index.js
import './main.less';
// ./import.less.js
module.exports = 'body { color: red; }';
// ./test-loader.js
module.exports = (source) => {
  console.log('It should call this loader', source);
  // parse content
  return source;
}

The error:

ERROR in ./main.less (./node_modules/css-loader/dist/cjs.js!./node_modules/less-loader/dist/cjs.js!./main.less)
Module build failed (from ./node_modules/less-loader/dist/cjs.js):


module.exports = 'body { color: red; }'
             ^
Unrecognised input
      Error in C:\Users\USER\Projects\less-issuer-test\import.less.js (line 1, column 15)
 @ ./main.less 2:12-125 9:17-24 13:15-29
 @ ./index.js 1:0-21
0

There are 0 best solutions below