首先,为避免TypeScript编译错误,让我展示在JavaScript中动态加载的示例。
_LoadedOnDemandModule.js
const DYNAMICALLY_LOADED_CONST_FROM_JS_MODULE_BY_DEFAULT = 'I was dynamically loaded from JS module by default!';
export default DYNAMICALLY_LOADED_CONST_FROM_JS_MODULE_BY_DEFAULT;
export const DYNAMICALLY_LOADED_CONST_FROM_JS_MODULE = 'I was dynamically loaded from JS module!';
index.js
loadDataOnDemand();
async function loadDataOnDemand() {
const MODULE = await import('./_LoadedOnDemandModule');
}
如果尝试使用console.log(MODULE)
,它会给出:
Module {default: "I was dynamically loaded from JS module by default!", __esModule: true, Symbol(Symbol.toStringTag): "Module"}
DYNAMICALLY_LOADED_CONST_FROM_JS_MODULE: (...)
default: "I was dynamically loaded from JS module by default!"
Symbol(Symbol.toStringTag): "Module"
__esModule: true
get DYNAMICALLY_LOADED_CONST_FROM_JS_MODULE: ƒ ()
__proto__: Object
以下针对TypeScript的解决方案适用于我,但我需要征求专业人员的确认,这里有一些关于不正确性的隐藏错误。
loadDataOnDemand1();
type TestType = {
default: string;
DYNAMICALLY_LOADED_CONST_FROM_JS_MODULE: string;
}
async function loadDataOnDemand1(): Promise<void> {
const MODULE: TestType = await import('./_LoadedOnDemandModule');
}