PirateApp
PirateApp

Reputation: 6250

How can I dynamically load svg icons from node_modules folder in my nuxt js component?

I am trying to use this library cryptocurrency-icons from Github inside my Nuxt SSR project

This library adds all the svg icons to ./node_modules/cryptocurrency-icons/svg/color directory

I made the following component in the components/BaseCryptoIcon.vue file

<template>
  <Component
    :is="
      require(`~/node_modules/cryptocurrency-icons/svg/color/${name}.svg`)
        .default
    "
    class="BaseIcon"
    v-bind="$attrs"
    @v-on="$listeners"
  />
</template>

<script>
/**
 * https://stackoverflow.com/questions/59148672/how-to-import-multiple-svgs-in-vue-js-via-vue-svg-loader
 */
export default {
  name: 'BaseIcon',

  // Transparent wrapper component
  // https://v2.vuejs.org/v2/guide/components-props.html#Disabling-Attribute-Inheritance
  inheritAttrs: false,

  props: {
    name: {
      type: String,
      required: true,
    },
  },
}
</script>

<style>
.BaseIcon {
  /* Add some default CSS declaration blocks */
  width: 32px;
  height: 32px;
}
</style>

When I try to use it in my pages/Index.vue file as following nothing is rendered. It is not giving any error either

<template lang="pug">
  base-crypto-icon(name='btc')
</template>

<script lang="javascript">
import BaseCryptoIcon from '~/components/BaseCryptoIcon.vue'
export default {
  components: {BaseCryptoIcon}
}
</script>

Can someone kindly tell me how I can make this work in Vue/Nuxt

Upvotes: 2

Views: 2266

Answers (1)

Andre Goulart
Andre Goulart

Reputation: 596

You can try to make method in components/BaseCryptoIcon.vue:

getIcon(name)  {
  return require(`~/node_modules/cryptocurrency-icons/svg/color/${name}.svg`).default
}

then in template:

 <Component
    :is="getIcon(name)"
  />

Probably related question from 2 days ago: Why image path is not resolved by require() when passed as prop in NuxtJS?

Upvotes: 3

Related Questions