javascript - React dynamic import does not accept string variable - Stack Overflow

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

I have a ponent which enables me to import images dynamically in react. This is the ponent 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 ponentDidMount() {
        try {
            const { resolve } = this.props;
            const { default: module } = await resolve();
            this.setState({ module });
        } catch (error) {
            this.setState({ hasError: error });
        }
    }

    ponentDidCatch(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 poent 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?

I have a ponent which enables me to import images dynamically in react. This is the ponent 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 ponentDidMount() {
        try {
            const { resolve } = this.props;
            const { default: module } = await resolve();
            this.setState({ module });
        } catch (error) {
            this.setState({ hasError: error });
        }
    }

    ponentDidCatch(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 poent 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?

Share Improve this question asked Jul 3, 2019 at 10:44 hoanhoan 1,4064 gold badges21 silver badges35 bronze badges 2
  • Strange - I can only assume that webpack translates the import string at pile time and so cannot figure out the path from a variable. – jsdeveloper Commented Jul 3, 2019 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 Commented Sep 4, 2022 at 3:34
Add a ment  | 

3 Answers 3

Reset to default 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.

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

const path = './test.jpg';
import(`${path}`);

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745451235a4628280.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信