Search code examples
javascriptsveltesapper

Import a folder of images


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'


Solution

  • 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="[..] />