我试图摆脱import语句,但希望动态加载Javascript文件。
我是用这门课来做的。
export function JSImport<T>(
importPromise: Promise<T>,
): Promise<T> {
// CommonJS's `module.exports` is wrapped as `default` in ESModule.
return importPromise.then((m: any) => (m.default || m) as T);
}无论如何,当导入的文件使用构造函数参数时,我会得到错误。
下面是旧用法(效果很好):
declare let Tiff: any;
const tiff = new Tiff({buffer: xhr.response});以下是新用法:
const importTiff = JSImport(
import(/* webpackChunkName: "Tiff" */ 'Tiff'),
);
try {
importTiff.then((Tiff: any) => {
const tiff = new Tiff({buffer: xhr.response});
....
}在新的代码线中,我得到了一个错误: TypeError:Tiff不是构造函数
在Chrome控制台中,Tiff变量看起来是这样的。

如何使用它作为构造函数?
发布于 2022-01-19 09:56:27
webpack动态导入import(/* chunkNameHint */ "moduleName")实际上提供了一个模块,您在JSImport函数中将其标识为泛型T:
export function JSImport<T>(
importPromise: Promise<T>, // TypeScript infers T to be the output of the dynamic import, i.e. the full module
): Promise<T>与其尝试自动“解压缩”模块(该模块可能具有默认导出和/或命名导出),您可以直接使用动态导入:
import(/* webpackChunkName: "Tiff" */ 'Tiff')
.then((module) => module.default) // Assuming the module has a default export and it is the one you need
.then((Tiff: any) => {
const tiff = new Tiff({buffer: xhr.response});
// ....
});https://stackoverflow.com/questions/70768023
复制相似问题