为@Stephan-v's solution +1,但这是针对 2021 年使用 Webpack 5 稍作修改的方法。
- 你的 Vue 组件
<template/>
选项 A:单个 SVG 文件
<template>
<svg viewBox="0 0 24 24">
<use :xlink:href="require('@/assets/icons/icon.svg')"></use>
</svg>
</template>
选项 B:SVG Sprite(例如,用于 FeatherIcons)
<template>
<svg viewBox="0 0 24 24">
<use
:xlink:href="require('@/assets/icons/sprite.svg') + `#${iconName}`"
></use>
</svg>
</template>
<script>
export default {
props: {
// Dynamic property to easily switch out the SVG which will be used
iconName: {
type: String,
default: "star",
},
},
};
</script>
- 您可能需要一个 Webpack 加载器。
注意:如果您使用的是 Vue 3(如上所述)或 Vite,则可能不需要 Webpack Loader。如果您使用的是 Storybook 或 Nuxt,您可能仍然需要它。
$ npm install svgo-loader -D
$ yarn add svgo-loader -D
webpack.config.js(或类似)
module.exports = {
mode: "development",
entry: "./foo.js",
output: {},
// ... other config ...
module: {
rules: [
/////////////
{
// Webpack 5 SVG loader
// https://webpack.js.org/guides/asset-modules/
// https://dev.to/smelukov/webpack-5-asset-modules-2o3h
test: /\.svg$/,
type: "asset",
use: "svgo-loader",
},
],
/////////////
},
};
- 完成!