gpt4 book ai didi

javascript - Webpack 通过变量动态地需要 npm 模块

转载 作者:行者123 更新时间:2023-11-30 19:50:19 25 4
gpt4 key购买 nike

我找不到通过变量动态要求 NPM 模块的方法。

这是我正在尝试做的示例代码,一切正常,期望动态导入 NPM 模块。

const firstModule = 'my-npm-module';
const secondModule = './MyReactComponent';

// NPM Module
import(firstModule).then(...); // Doesn't work
import('my-npm-module').then(...); // Works

// Local React Component
import(secondModule).then(...); // Works
import('./MyReactComponent').then(...); // Works

最佳答案

来自Webpack docs关于动态导入:

Fully dynamic statements, such as import(foo), will fail because webpack requires at least some file location information. This is because foo could potentially be any path to any file in your system or project. The import() must contain at least some information about where the module is located, so bundling can be limited to a specific directory or set of files.

您最好的选择可能是不对 node_modules 中的任何内容使用动态加载,或者添加模块的显式路径,例如

import(`./node_modules/${firstModule}/index.js`);

关于javascript - Webpack 通过变量动态地需要 npm 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54553721/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com