Answer the question
In order to leave comments, you need to log in
How to dynamically import an image?
Hello.
Please tell me, I use this flags library https://github.com/hampusborgos/country-flags/tree...
I have an array with data containing the name of the images.
For example
, I need to display an image from there in a loop.
I am using webpack.
If I import at the beginning of the script
For example like this It
turns out to be done like this
But I don’t understand how to import in a loop and exactly the images that I need.
let arr = ["ru","us"]
import ru from "svg-country-flags/svg/ru.svg";
<img :src='ru'/>
Answer the question
In order to leave comments, you need to log in
Modules are imported statically, before any code is executed. There is a dynamic asynchronous import
option . But this method has the main disadvantage: WebPack will collect all files with flags in a separate chunk, and the bundle will be heavy.
If you want beauty, you can get confused and add a module where imports and then exports of all flags are registered. Type import(moduleName)
import ru from "svg-country-flags/svg/ru.svg";
import ua from "svg-country-flags/svg/ua.svg";
// ...
// и там же экспорты:
export ru;
export ua;
// ...
import { ru, ua } from './mySuperModule';
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question