8

I have a fairly complicated loader setup for style sheets:

  {
    test: /\.scss$/,
    loader: ExtractTextPlugin.extract("style",
      "css?sourceMap&localIdentName=[path][name]__[local]__[hash:base64:5]!sass?outputStyle=expanded&" +
      "includePaths[]=" + other stuff)
    )
  }

Which works great, but on some requires I want to add the modules option to css-loader, so it'd look like this:

require('./foo.scss!css?modules&sourceMap&localIdentName=[path][name]__[local]__[hash...');

But I can't do this all over the place.

How can I configure this so that I can enable the css-loader modules flag on certain requires while keeping the rest of it the same?

Maybe something like a loader 'alias', e.g. require('./foo.scss!my-scss-with-modules-flag-alias')?

The only solution I can think of is writing a loader that does a syntax transform to inline the loader config into certain require calls... but that's brittle and complicated.

Brigand
  • 84,529
  • 20
  • 165
  • 173

2 Answers2

16

resolveLoader.alias will work here. Ie.

resolveLoader: {
    alias: {
        'with-modules': 'loader definition goes here',
    }
}

Using this configuration you can do simply

require('with-modules!./foo.scss');

at your code.

Juho Vepsäläinen
  • 26,573
  • 12
  • 79
  • 105
  • 3
    How did you get to this solution? Webpack is amazing, bug I am having a hard time with the documentation ... – Carlos Morales Jul 22 '15 at 08:42
  • 1
    Well, I'm authoring webpack related books so it's sort of my job to know these things. I did add a note about this to the documentation as it was missing earlier. I agree the documentation can be a bit opaque. – Juho Vepsäläinen Jul 22 '15 at 08:51
  • 1
    @JuhoVepsäläinen: Can you expand on your answer. What would go in the definition? If I try to create an alias with "style!css?modules!postcss", I get an error: Cannot resolve module 'style!css'. – Jacob T. Nielsen Jul 22 '16 at 09:03
  • 1
    @JacobT.Nielsen As far as I understand, you can alias just a loader name, not a chain like that. I tried aliasing a chain a while ago and it failed. I even opened an issue about that as it would be handy. – Juho Vepsäläinen Jul 22 '16 at 09:04
1

The resolveLoader.alias might work in the given case, since you are using a plugin as the loader. However if you need to use a chain of loaders, it will not work. (There's a feature request on it: https://github.com/webpack/webpack/issues/2772).

Instead you can add a parameter to the file in the require statement

var styles = require('./foo.scss?modules');

And create a new loader rule:

module: {
    loaders: [
        ...
        { test: /\.scss$/, loader: 'style!css!postcss!sass' },
        { test: /\.scss\?modules$/, loader: 'style!css?modules!postcss!sass' }
    ]
}
Jeppe Stougaard
  • 412
  • 3
  • 8
  • 1
    Couldn't get this to work using Webpack 3. It always selected the first loader as if it was ignoring the query params. – Ryall Feb 27 '18 at 12:39