问题描述
这是我的用例:大多数 svg 应该内联.所以我设置了这样的规则:
Here's my use-case: Most svgs should be inlined. So I setup a rule like this:
{test: /\.svg$/, use: "svg-inline-loader"},
在某些情况下,我只想要 svg 的 url 而不是内联它.在 webpack 1.x 中,我这样要求它们:require('path/to/file.svg?external')
.
In some instances I just want the url of an svg rather than inlining it.In webpack 1.x I required them like this: require('path/to/file.svg?external')
.
这是相应的规则:
{test: /\.svg\?external$/, use: "file-loader!image-webpack-loader"},
似乎 webpack 2 在对规则进行 test
时不再包含 ?
部分,因为只有第一条规则应用于 all 迁移后我的 svgs.
It seems like webpack 2 does not include the ?
part anymore when test
ing for a rule since only the first rule is being applied to all my svgs after migrating.
有没有办法解决这个问题?require
时,是否有不同的策略可以为相同扩展名的文件应用不同的加载器集?
Is there a way around this? Is there maybe a different strategy of how to apply different set of loaders for files of the same extension when require
ing them?
PS:我知道我可能需要这样的文件:require('!file-loader!image-webpack-loader!path/to/file.svg')
但我的加载器比这更复杂一些,我不想一直重复它们的配置.
PS: I'm aware that I could require the file like this: require('!file-loader!image-webpack-loader!path/to/file.svg')
but my loaders are a bit more complex than this and I don't want to repeat their configuration all the time.
PSS:这似乎也不起作用(它仍然只适用第一条规则)
PSS: This doesn't seem to work either (it still only applies the first rule)
{test: /\.svg$/, use: "svg-inline-loader", exclude: /\?external/},
{test: /\.svg$/, use: "file-loader?!image-webpack-loader", include: /\?external/}
推荐答案
所以我最近参加了 webpack 的 Juho Vepsäläinen 的演讲,并在 这张幻灯片:
So I recently attended a talk by webpack's Juho Vepsäläinen and found the answer in this slide:
{
test: /.css$/,
oneOf: [
{
resourceQuery: /inline/, // foo.css?inline
use: 'url-loader',
},
{
resourceQuery: /external/, // foo.css?external
use: 'file-loader',
},
],
}
resourceQuery 来救援!
这篇关于Webpack 2+:如何为具有相同扩展名的文件应用不同的加载程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!