Skip to content

Can't load SVG using Vite #88

@kamil-hammouche

Description

@kamil-hammouche

Hello,

I can't manage to load SVG using @nuxtjs/svg. I've added properly the build module in the nuxt.config.js file and they still don't load.
I've seen some dev complaining that this might be due to ViteJS, so I aswell added the vite-svg-loader dependency but I have this error:

__vite_ssr_import_0__.createElementVNode is not a function

Here's my nuxt.config.js file

import svgLoader from 'vite-svg-loader'
import { APP_NAME, APP_LANG, APP_ROOT_ID } from "./constants";

export default {
  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    title: APP_NAME,
    htmlAttrs: {
      lang: APP_LANG,
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' },
      { name: 'format-detection', content: 'telephone=no' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  globals: {
    id: globalName => APP_ROOT_ID,
  },

  // Global CSS: https://go.nuxtjs.dev/config-css
  css: [
    '@/assets/styles/main.scss',
    '@/assets/styles/variables.scss',
  ],

  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
  ],

  // Auto import components: https://go.nuxtjs.dev/config-components
  components: {
    dirs: [
      '~/components',
      '~/components/pages',
      '~/components/ui',
    ],
  },

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [
    // https://go.nuxtjs.dev/eslint
    '@nuxtjs/eslint-module',
    // https://go.nuxtjs.dev/tailwindcss
    '@nuxtjs/tailwindcss',
    '@nuxtjs/svg',
    '@nuxtjs/style-resources',
    'nuxt-vite'
  ],

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [],

  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
    extend(config, ctx) {
      config.module.rules.push({
        test: /\.svg$/,
        loader: 'file-loader',
      });
    },
  },

  styleResources: {
    scss: '@/assets/styles/mixins.scss',
  },

  vite: {
    ssr: false,
    plugins: [svgLoader()],
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '@import "@/assets/styles/mixins.scss";',
        },
      },
    },
  },
}

And here's how I load my SVGs :

Icon.vue

<template>
  <component :is="icon"/>
</template>

<script>
import * as icons from "~/assets/images/icons";

export default {
  props: [ 'name' ],
  computed: {
    icon() {
      return icons[this.name]
    }
  },
}
</script>

Usage :

<template>
  <Icon name='add' />
</template>

Best regards,

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions