What is the loader order for webpack?

Webpack

Webpack Problem Overview


When I have a loader configuration with multiple tests matching a file, I would expect only the first matching loader to be used but that doesn't seem to be the case.

I tried reading the source but even when I found the bit that I think implements the loading I can't understand how it behaves.

The documentation doesn't mention how that situation should behave either.

Webpack Solutions


Solution 1 - Webpack

{
    test: /\.css$/,
    loaders: ['style'],
},
{
    test: /\.css$/,
    loaders: ['css'],
},

and

{
    test: /\.css$/,
    loaders: ['style', 'css'],
},

appear to be equal. In function terms, this is the same as style(css(file)) (thanks Miguel).

Note that within loaders they are evaluated from right to left.

Solution 2 - Webpack

Official documentation explains it really well. Unfortunately all the necessary info are spread in different sections of documentation. Let me wrap up all that you need to know.

> Make sure they are in correct order (bottom to top).

> They are functions that take the source of a resource file as the > parameter and return the new source.

> Loaders can be chained. They are applied in a pipeline to the > resource. The final loader is expected to return JavaScript; each > other loader can return source in arbitrary format, which is passed to > the next loader.

So...

If you have somefile.css and you are passing it through loaderOne, loaderTwo, loaderThree is behaves like a regular chained function.

{
    test: /\.css$/,
    loaders: ['loaderOne', 'loaderTwo', 'loaderThree']
}

means exactlly the same as...

loaderOne(loaderTwo(loaderThree(somefile.css)))

If you are coming from grunt || gulp world it is confusing. Just read loaders order from right to left.

Solution 3 - Webpack

This answer was helpful to me but I'd like to complement with another point which affects loader order, which is the loadername! approach.

Let's say you have an url-loader in your config with an higher priority than file-loader and you'd like to import an image path with the latter. Doing nothing would import the file via url-loader (which creates an encoded data-url).

Prefixing the import with file-loader! would direct the import to that loader.

import image from 'file-loader!./my-img.png'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionw00tView Question on Stackoverflow
Solution 1 - WebpackJuho VepsäläinenView Answer on Stackoverflow
Solution 2 - WebpackPaweł GrzybekView Answer on Stackoverflow
Solution 3 - WebpackE. SundinView Answer on Stackoverflow