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.

Constant Meiring
  • 3,285
  • 3
  • 40
  • 52
  • Maybe will help you https://stackoverflow.com/questions/49568377/imports-not-recognizing-image-modules-in-react-using-webpack-with-typescript/49568518#49568518 – Tan Duong Apr 19 '18 at 10:07
  • Are the filenames of the svgs known ahead of time? – altShiftDev Apr 19 '18 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. – Constant Meiring Apr 19 '18 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'` – altShiftDev Apr 19 '18 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. – altShiftDev Apr 19 '18 at 15:53
  • They get imported for both caching and use within templates (without knowing filenames beforehand), so it's a bit tricky. – Constant Meiring Apr 22 '18 at 09:51

0 Answers0