Adding inline SVG to your Nuxt3 Vite project: a step-by-step guide
P粉471207302
P粉471207302 2023-11-04 13:36:38
0
2
734

Hi, I'm having trouble importing inline svgs into my nuxt3 vite project. Any advice would be greatly appreciated.

I found this works but I need an inline item. So I would do something like

and do something like this (require doesn't work in vite).


setup(props) {
        const currentIcon = computed(() => {
            return defineAsyncComponent(() =>
                import(`~/assets/images/icons/push-icon-chatops.svg'?inline`)
            );
        }).value;

        return {
            currentIcon,
        };
    },

But I found that the way vite is imported is strange, the result is either the url string displayed in v-html, or an unreadable object

I'm trying to use this plugin but without success.

https://github.com/nuxt-community/svg-module

P粉471207302
P粉471207302

reply all(2)
P粉269530053

For the TS Nuxt 3 project, the situation is as follows.

nuxt.config.ts File:

import svgLoader from 'vite-svg-loader'

export default defineNuxtConfig({
  // Rest of your config.
  vite: {
    plugins: [
      svgLoader({
       // Your settings.
      }),
    ],
  },
})

Component example:

<template>
  <div>
    <ArrowLeft />
  </div>
</template>

<script setup lang="ts">
import ArrowLeft from '../assets/svg/arrow-left.svg?component'
</script>

Note that the last ?component is very important, otherwise TS will report an error.

Plug-in documentation: vite-svg-loader

P粉242535777

It appears that vite is actually incompatible with the @nuxtjs/svg plugin. So the answer is to install a vite specific plugin, in this case I installed the vite plugin and then did this

vite: {
    plugins: [
        svgLoader()
    ]
},
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template