How to import svg files in Vue 3?
P粉021854777
2023-08-23 08:37:27
<p>I tried the following: <br /> <a href="https://github.com/visualfanatic/vue-svg-loader/tree/master">https://github. com/visualfanatic/vue-svg-loader/tree/master</a></p>
<p>But because vue-template-compiler is used in Vue 2, there is a version conflict. </p>
<p>I tried:<br /> <a href="https://github.com/visualfanatic/vue-svg-loader">https://github.com/visualfanatic/vue- svg-loader</a></p>
<p>But I'm missing a specific Vue dependency. </p>
<p>I noticed that there is a note when using TypeScript, which requires declaring a type definition file. However, I still get the "Cannot find module '../../assets/myLogo.svg' or its corresponding type declaration" error. </p>
<p>This is what I added: </p>
<p>vue.config.js</p>
<pre class="brush:php;toolbar:false;">module.exports = {
chainWebpack: (config) =>
{
const svgRule = config.module.rule('svg');
svgRule.uses.clear();
svgRule
.use('vue-loader-v16')
.loader('vue-loader-v16')
.end()
.use('vue-svg-loader')
.loader('vue-svg-loader');
},
configureWebpack: process.env.NODE_ENV === 'production' ? {} : {
devtool: 'source-map'
},
publicPath: process.env.NODE_ENV === 'production' ?
'/PersonalWebsite/' : '/'
}</pre>
<p>shims-svg.d.ts</p>
<pre class="brush:php;toolbar:false;">declare module '*.svg' {
const content: any;
export default content;
}</pre>
<p>MyComponent.vue</p>
<pre class="brush:php;toolbar:false;"><template>
<div>
<MyLogo />
</div>
</template>
<script lang="ts">
import * as MyLogo from "../../assets/myLogo.svg";
export default defineComponent({
name: "MyComponent",
components: {
MyLogo
},
props: {
},
setup(props)
{
return {
props
};
}
});
</script></pre>
<p><br /></p>
vue-svg-loader is not compatible with vue 3. To import an svg and use it as a component, just wrap the file contents in 'template'
In component:
Webpack:
scripts/svg-to-vue.js:
In fact, Vue CLI already supports SVG natively. It uses file-loader internally. You can confirm by running the following command on the terminal:
If "svg" is listed (it should be), then you only need to:
So if your purpose is just to display SVG, you don't need any third-party libraries.
Of course, in order to satisfy the TypeScript compiler’s type declaration requirements: