Aleksandr
Aleksandr

Reputation: 61

Import SVG as a module in Vite.js 2.9 and Vue.js 2.7

I am moving my project dependencies from Vue CLI to Vite. I have to use Vue.js 2.7 at the moment and I cannot upgrade to Vue.js 3 yet.

I used vue-svg-loader with Vue CLI previously and I am trying to use vite-svg-loader now. It looks like vite-svg-loader supports Vue.js 3 only.

Is there a different way to import SVG files with Vite & Vue.js 2.7? I have many of them and I will not be able to replace them with .vue components.

This is how I import and use SVG files in my components:

<template>
  <div>
    <my-icon/>
  </div>
</template>

<script>
import MyIcon from "@some_path/my-icon.svg";

export default {
    components: {
        MyIcon
    }
};
</script>

Vite doesn't treat these SVG files as Vue components. Instead, it treats them as static assets and creates something like assets/my-icon.7f263221.svg.

Upvotes: 2

Views: 2123

Answers (1)

liRONCO11
liRONCO11

Reputation: 196

I've encountered the same problem, https://www.npmjs.com/package/vite-plugin-vue2-svg

// vite.config.ts
import { defineConfig } from "vite";
import { createVuePlugin } from "vite-plugin-vue2"; // vue2 plugin
import { createSvgPlugin } from "vite-plugin-vue2-svg";

export default defineConfig({
  plugins: [createVuePlugin(), createSvgPlugin()],
});

<!-- App.vue -->
<template>
  <Icon />
 </template>
<script>
import Icon from "./icon.svg";

export default {
  components: {
    Icon,
  },
};
</script>

Upvotes: 3

Related Questions