1

I have a Svelte+Sapper project in which this works just fine:

import logotype from 'images/logo_vertical.svg';

[..]

<img src={logotype} alt="..." />

But is it possible to import an entire folder as such:

import logotypes from 'images/logotypes';

.. and use them like this:

<img src={logotypes.logo1} alt="..." />

or

<img src={logotypes['logo1.svg']} alt="..." />

I have tried importing like this but it does not work since it is then looking for a module rather than a set of images: import logotypes from 'images/logotypes';

'images/logotypes' is imported by ....svelte, but could not be resolved – treating it as an external dependency

And in runtime...

Error: Cannot find module 'images/logotypes'

Marcus
  • 8,230
  • 11
  • 61
  • 88
  • 1
    It's not possible to import a folder that way. You could create an intermediary module file as described here: https://stackoverflow.com/a/29722646/1870780 as an alternative. – juliomalves Jan 06 '21 at 17:58
  • 2
    There is a babel-plugin called [import-all.macro](https://github.com/kentcdodds/import-all.macro). – CD.. Jan 07 '21 at 06:21

1 Answers1

1

Following your idea Julio Malves, this is what I came up with (in file/images/logos/index.js):

import logo1 from './logo_1.svg'
import logo2 from './logo_2.svg'
import logo3 from './logo_3.svg'
import logo4 from './logo_4.svg'
import logo5 from './logo_5.svg'
import logo6 from './logo_6.svg'

export default {
    logo1,
    logo2,
    logo3,
    logo4,
    logo5,
    logo6,
}

And using it like;

import logos from 'images/logos'

[..]

<img src="{logos.logo1}" alt="[..] />
Marcus
  • 8,230
  • 11
  • 61
  • 88
  • 1
    I think it's the best solution. This could be automatized by generating this code with a Node script (maybe going fancy, with a file watcher on the folder and all). This could also be automatized further with a bundler plugin, to detect that you are trying to import a folder, but this one doesn't seem like a good idea -- this would fragilise your build setup, and risk conflicts (with the index.js of the folder, and how can you tell that when you're trying to import a folder, that's for the images?). I think you should accept this answer. – rixo Jan 08 '21 at 11:53
  • If I would have hundreds of resources I probably would automate it but this works for now, thanks for confirming the solution, if no one comes up with anything better I´ll accept this as the best solution. – Marcus Jan 08 '21 at 13:30