E
E
Enickckey2022-04-12 18:10:22
Vue.js
Enickckey, 2022-04-12 18:10:22

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

1 answer(s)
S
Sergey Sokolov, 2022-04-12
@enickckey

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;
// ...

Then it will be enough to import the necessary flags in one line . And Webpack will figure it out and include only the necessary ones in the bundle. When you write such a helper module, please send a pull-request to that repo. import { ru, ua } from './mySuperModule';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question