w00t
w00t

Reputation: 18281

What is the loader order for webpack?

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.

Upvotes: 104

Views: 44474

Answers (4)

Rudy Huynh
Rudy Huynh

Reputation: 608

Webpack document now has this Pitching Loaders section. If the loader exposes pitch function, the order of pitch function will be from left to right (or top to bottom). And:

if a loader delivers a result in the pitch method, the process turns around and skips the remaining loaders

Upvotes: 1

E. Sundin
E. Sundin

Reputation: 4181

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'

Upvotes: 4

Paweł Grzybek
Paweł Grzybek

Reputation: 1113

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.

1.

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

2.

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

3.

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.

Upvotes: 82

{
    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.

Upvotes: 128

Related Questions