4

I have a component which enables me to import images dynamically in react. This is the component I am using:

import React from "react";
import PropTypes from "prop-types";

// Lazily load an iamge
class LazyImageLoader extends React.Component {
    constructor() {
        super();
        this.state = {
            module: null,
        };
    }

    async componentDidMount() {
        try {
            const { resolve } = this.props;
            const { default: module } = await resolve();
            this.setState({ module });
        } catch (error) {
            this.setState({ hasError: error });
        }
    }

    componentDidCatch(error) {
        this.setState({ hasError: error });
    }

    render() {
        const { module, hasError } = this.state;

        if (hasError) return <div>{hasError.message}</div>;
        if (!module) return <div>Loading module...</div>;

        if (module) return <img src={module} alt="Logo" />;

        return <div>Module loaded</div>;
    }
}

LazyImageLoader.propTypes = {
    resolve: PropTypes.func.isRequired,
};

export default LazyImageLoader;

Now, if I try to use this compoent like this with a string to the image which should get imported it works perfectly fine:

<LazyImageLoader resolve={() => import("assets/images/os/netboot.svg")} />

But as soon as I extract the URL into a seperate variable it no longer works and I get the error message "cannot find module ...":

const path = "assets/images/os/netboot.svg";
<LazyImageLoader resolve={() => import(path)} />

Is there a way I can use variables for a dynamic import?

hoan
  • 1,277
  • 3
  • 18
  • 32
  • Strange - I can only assume that webpack translates the import string at compile time and so cannot figure out the path from a variable. – jsdeveloper Jul 03 '19 at 10:58
  • Did you ever get it to work? Other Answer say using a template string literal would work? Does it? Or maybe just using Vite would work. – SeanMC Sep 04 '22 at 03:34

3 Answers3

2

According to the answer in:

Dynamic imports in ES6 with runtime variables

"The rules for import() for the spec are not the same rules for Webpack itself to be able to process import()".

So no you can't use variables with webpack dynamic import statements.

Stompy32
  • 99
  • 6
0

It doesn't work directly to use the variable but could be used as follows -

const path = './test.jpg';
import(`${path}`);
Monika Mangal
  • 1,665
  • 7
  • 17
0

You can do it with Vite. The example they cite uses a template string literal, but that shouldn't obligate you to use a prefix or something. You probably would anyway. Here is the docs and their example.

https://vitejs.dev/guide/features.html#dynamic-import

const module = await import(`./dir/${file}.js`)

It also seems like, with glob imports also described on that docs page, you have lots of other options to do it lots of ways.

SeanMC
  • 1,960
  • 1
  • 22
  • 33