1

I have this image folder:

- country
  - EN
  - FR
  - IT

I want to import an image this way:

import image from "./country/{country}/test.png";

How can I do this?

HelloWorld
  • 4,671
  • 12
  • 46
  • 78
  • 1
    You can import images using [dynamic imports](https://webpack.js.org/api/module-methods/#import-) – Agney Jun 17 '18 at 14:53
  • This might answer your question: https://stackoverflow.com/questions/42118296/dynamically-import-images-from-a-directory-using-webpack – Anbarasi U Jun 17 '18 at 15:10
  • @AnbarasiU What exactly detail about your links content should help me? There are many good/bad tips inside. – HelloWorld Jun 17 '18 at 18:32
  • @BoyWithSilverWings So I can just do: import json from `./locale/${language}.json`) as a dynamic json example... ? As destoryer said import is for javascript files but not for images.. – HelloWorld Jun 17 '18 at 18:36
  • You will have to install [babel](https://babeljs.io/docs/en/babel-plugin-syntax-dynamic-import/) plugin before though. `webpack` actually considered everything as a javascript file itself before, so it does not count – Agney Jun 18 '18 at 04:05

1 Answers1

2

i will always use both of the methods (require, import). first thing is i do categorise images in 2 ways:

  1. what i am using so may times and using it frequently.
  2. what is rarely used.

then i will create an js file in that i do import all 1'st kind of images (frequently used). When project will load it will execute all import statements first so that time my all of the images are imported already so then whenever i need this images i do get that image from utility what i have created for importing images. that util file will be kind of this:

import CSK from "../assets/images/teamLogo/CSK.png";
import CSK_bw from "../assets/images/teamLogo/CSK-bw.png";

export function getImage(name) {
  switch (name) {
    case "CSK":
      return CSK;
    case "CSK_bw":
      return CSK_bw;
    }
  }

so whenever i need image i just import above function with image name.

and second category images i will use as require.

Shubhanu Sharma
  • 1,957
  • 12
  • 30
  • That means importing same image for 10 countries and then switch case them ? Is that not costly? furthermore doing a switch case for each logo/image etc... is boilerplate which should be solved in a different way. – HelloWorld Jun 17 '18 at 18:30