0

I need to be able to apply some pre-processing (a string replace) to .less files that are pulled in for compile, but before the less-loader applies its own processing.

Initially I thought I could do:

test: /\.less/, include: /SomeDir/, use: ['style-loader', 'css-loader', 'less-loader', {
  loader: 'string-replace-loader', options: { /* ... */ }
}]

However, observing the input to string-replace-loader shows it's just a list of filenames, which obviously won't work.

I'm hoping I can do something with raw-loader and pipe the output into less-loader after the pre-processing, but I'm not sure how to tell the latter to accept raw input instead of the files.

Dan
  • 1,130
  • 2
  • 20
  • 38

1 Answers1

1

I think that I've figured this one out. I ended up rummaging through the source of the less compiler to see what plugin format it expects.

The code below fakes a full plugin, and just provides the basic required methods. It currently does a single string replace (possible regex), but of course can be swapped for whatever you need.

test: /\.less/, include: /SomeDir/, use: ['style-loader', 'css-loader', {
    loader: 'less-loader',
    options: {
        plugins: [
            {
                install: (lessObj, pluginManager) => {
                    pluginManager.addPreProcessor({
                        process: function (lessCode) {
                            return lessCode.replace('Replace this', 'With this');
                        }
                    }, 2000); // 2000 sets priority to come after less imports, per code comments
                }
            }
        ]
    }
}]

Ideally, this would be moved out of the config file, especially if it gets larger.

Dan
  • 1,130
  • 2
  • 20
  • 38
  • To add to this: if you want to replace all instances of the string in file, the first argument to `string.replace` needs to be a Regex with the global flag. – Sander Dec 06 '19 at 15:31
  • The other priorities can be found here https://pub.dev/documentation/less_dart/latest/less/PluginManager/addPreProcessor.html – Sander Dec 06 '19 at 15:31