search

Home  >  Q&A  >  body text

Adding inline SVG to your Nuxt3 Vite project: a step-by-step guide

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粉471207302P粉471207302481 days ago808

reply all(2)I'll reply

  • P粉269530053

    P粉2695300532023-11-05 12:52:21

    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

    reply
    0
  • P粉242535777

    P粉2425357772023-11-05 12:34:07

    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()
        ]
    },

    reply
    0
  • Cancelreply