Webpack 的加载程序订单是什么?

当我有一个包含多个测试的加载程序配置来匹配一个文件时,我希望只使用第一个匹配的加载程序,但是情况似乎并非如此。

我尝试阅读 源头,但即使当我发现位,我认为实现了加载,我不能理解它的行为。

文档 也没有提到这种情况应该如何表现。

38617 次浏览
{
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.

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.

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'