[英]Adding SVG Loader to Vue-cli project for a specific directory only
I am using Vue 2.6.10 in a vue-cli project.我在 vue-cli 项目中使用 Vue 2.6.10。 I want to use an SVG Loader in this project for SVG files from a specific directory only .
我想在这个项目中使用 SVG 加载器仅用于特定目录中的 SVG 文件。 These are my current rules in
vue.config.js
这些是我当前在
vue.config.js
中的规则
chainWebpack: (config) => {
const svgRule = config.module.rule('svg')
svgRule.uses.clear()
svgRule
.use('vue-svg-loader')
.loader('vue-svg-loader')
},
This works - but runs on all SVG files.这有效 - 但在所有 SVG 文件上运行。
I've seen some include and exclude rules for webpack, but I am not sure how you would apply them in this context.我已经看到 webpack 的一些包含和排除规则,但我不确定您将如何在这种情况下应用它们。
https://github.com/neutrinojs/webpack-chain is in use here. https://github.com/neutrinojs/webpack-chain在这里使用。 The issue that I have is that after adding a restriction for
vue-svg-loader
I had to define the file-loader
rule for all the other svg files.我遇到的问题是,在为
vue-svg-loader
添加限制后,我必须为所有其他 svg 文件定义file-loader
规则。
I have two folders, /icons/inline
for vue-svg-loader
and /icons/plain
for the default svgs that have to be served as files.我有两个文件夹,
/icons/inline
用于vue-svg-loader
和/icons/plain
用于必须作为文件提供的默认 svg。 This one works for me:这个对我有用:
chainWebpack: (config) => {
config.module.rule('svg').uses.clear()
config.module
.rule('svg')
.test(/\/icons\/inline\/.*\.svg$/)
.use('babel-loader')
.loader('babel-loader')
.end()
.use('vue-svg-loader')
.loader('vue-svg-loader')
.end()
config.module
.rule('svg-file')
.test(/\/icons\/plain\/.*\.svg$/)
.use('file-loader')
.loader('file-loader')
.end()
}
I spent a long while trying to solve a similar problem myself.我花了很长时间试图自己解决类似的问题。
Here's my solution:这是我的解决方案:
chainWebpack: config => {
/**
* Ignore icons in the regular SVG rule
*
* It is necessary to use RegExp rather than a string literal
* as WebPack complained about '!' being a reserved character
* when using literals
*/
config.module.rule('svg').test(new RegExp(/^((?!\/icons\/).)*(svg)(\?.*)?$/));
//Create a new rule for icons that converts them into Vue templates
const svgIconRule = config.module.rule('svg-icon').test(new RegExp(/^.*(\/icons\/).*(svg)(\?.*)?$/));
svgIconRule.uses.clear();
svgIconRule.delete('type');
svgIconRule.delete('generator');
//Add replacement loader
svgIconRule
.use('vue-loader')
.loader('vue-loader')
.end()
.use('vue-svg-loader')
.loader('vue-svg-loader')
.end()
;
}
This will load all SVGs that don't contain icons in their path from the standard loader, and use vue-svg-loader
for those that do.这将从标准加载器加载路径中不包含图标的所有 SVG,并使用
vue-svg-loader
那些包含图标的 SVG。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.