1

I'd like to import a directory full of SVG assets, and reference those as an array within my VueJS component. Something like the following:

//LevelComponent.vue

<template>
  <div v-html="image"></div>
</template>

<script>
import * as levels from '@/assets/levels/*.svg'

export default {
  name: "Level",
  data() {
    return {
      image: ''
    }
  },
  methods: {
    setLevel(levelNumber) {
      this.level = levels[levelNumber];
    }
  }
}
</script>

The above obviously doesn't work because of how VueJS/Webpack handles asset paths:

Module not found: Error: Can't resolve '@/assets/levels/*.svg'

We currently load the SVGs separately, but this requires a update in our code every time the contents of the directory changes:

import level1 from '@/assets/levels/1.svg'
import level2 from '@/assets/levels/2.svg'
import level3 from '@/assets/levels/3.svg'

Other than the above error, I'm pretty sure I'm going about this the wrong way. What would the correct way be to approach this? I should mention we currently use svg-inline-loader in Webpack to load the individual SVGs.

6
  • Maybe will help you stackoverflow.com/questions/49568377/… Commented Apr 19, 2018 at 10:07
  • Are the filenames of the svgs known ahead of time? Commented Apr 19, 2018 at 14:19
  • @Scott Ideally, no. It would be great for it to simply autoload all files in the folder. A colleague today suggested that we generate the JS to load the files outside of Vue, and then insert it at a placeholder in the Vue component before it compiles. I might just go down that route if I don't find something nicer. Commented Apr 19, 2018 at 15:47
  • @ConstantMeiring webpack handles dynamic assets differently, in my project whenever I'm importing something like *.svg I must use the relative path to the assets folder: import * as levels from '../assets/levels/*.svg' Commented Apr 19, 2018 at 15:51
  • If you're importing them in order to speed up load times (caching) then that's one thing, but if your importing them just to use in a v-for then there are other solutions I can suggest, esp if you have predictable file-names. Commented Apr 19, 2018 at 15:53

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.