Use LESS stylesheets in VS2017 Angular 5 project

267 Views Asked by At

I believe it should be easier than it looks. I'm new to webpack and I spent hours trying to figure out what I'm missing.

All I need is to add LESS preprocessor to webpack.config.js. Rule for CSS is already there and it works:

module: {
        rules: [
            { test: /\.css$/, use: ['to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize'] }
        ]
    }

But once added very basic rule for less-loader, like { test: /\.less$/, use: 'less-loader' } (I've tried numerous variations of this rule), I always get an error You may need an appropriate loader to handle this file type on my LESS stylesheet. Really? I'm providing the loader, what else it needs?

I'm trying to use my stylesheet in Angular component like so:

@Component({
    styles: [require('./my.component.less')]
})

Exact error:

NodeInvocationException: Prerendering failed because of error: Error: Module 
parse failed: Unexpected token (1:1)
You may need an appropriate loader to handle this file type.
// few lines of my styleshhet, so it was indeed located properly
// call stack ... at Object.module.exports ... at __webpack_require__...
1

There are 1 best solutions below

0
On

Finally, I got it fully working. It took hours and I haven't found everything in one place, so I'm posting full answer here.

TL;DR This is working configuration in webpack.config.js, use it in sharedConfig.module.rules collection:

{
    test: /\.less$/, use: [
    { loader: "to-string-loader" },
    { loader: isDevBuild ? 'css-loader' : 'css-loader?minimize' },
    {
         loader: "less-loader",
         options: {
             fallback: isDevBuild ? 'css-loader' : 'css-loader?minimize'
         }
     }]
}

Gotchas here:

  1. Trying to use it in client bundle configuration, I got "You may need an appropriate loader to handle this file type" on prerendering
  2. Trying to use it without fallback option, I got "window is not defined" on prerendering
  3. You need all three loaders in line, otherwise also doesn't work
  4. I believe minification will work as expected, however have not tested yet.