下面的代码似乎使用了动态导入:
(function executeApplication(): void {
const loadDataButton: HTMLElement | null = document.getElementById("LoadDataButton");
if (loadDataButton !== null) {
loadDataButton.addEventListener("click", (): void => {
(async function handler(): Promise<void> {
console.log("Checkpoint 1");
const loadedValue: string = await loadDataOnDemand();
console.log(loadedValue);
})().catch((): void => { /* */ });
});
}
})();
async function loadDataOnDemand(): Promise<string> {
console.log("Checkpoint 2");
const MODULE: { default: string; DYNAMICALLY_LOADED_CONST_FROM_TS_MODULE: string; } =
await import("./DynamicLoadingTesting/TypeScriptModuleForDynamicLoading");
console.log("Checkpoint 3");
console.log(MODULE);
return MODULE.DYNAMICALLY_LOADED_CONST_FROM_TS_MODULE;
}
但是实际上TypeScriptModuleForDynamicLoading.ts
已经捆绑到了入口点:
FrontendLogicPreProcessingTesting:
asset FrontendLogicPreProcessingTesting.js 11.2 KiB [emitted] (name: FrontendLogicPreProcessingTesting)
./FrontendLogicPreProcessingTesting.ts 2.28 KiB [built] [code generated]
./DynamicLoadingTesting/TypeScriptModuleForDynamicLoading.ts 419 bytes [built] [code generated]
FrontendLogicPreProcessingTesting (webpack 5.4.0) compiled successfully in 710 ms
没有webpack错误,并且在浏览器中的输出似乎是正确的:
我的Webpack配置:
{
name: 'FrontendLogicPreProcessingTesting',
context: 'D:\\IntelliJ IDEA\\XXXXX\\ProjectBuildingCommonTest\\00-Source\\FrontendLogicPreProcessingTesting'
,
target: 'web',
entry: {
FrontendLogicPreProcessingTesting: 'D:/IntelliJ IDEA/XXXXX/ProjectBuildingCommonTest/00-Source/FrontendLogic
PreProcessingTesting/FrontendLogicPreProcessingTesting.ts'
},
output: {
path: 'D:\\IntelliJ IDEA\\XXXXX\\ProjectBuildingCommonTest\\01-DevelopmentBuild\\FrontendLogicPreProcessin
gTesting',
publicPath: './',
filename: '[name].js',
chunkFilename: 'loading_on_demand/partial__[id].js'
},
mode: 'development',
watch: true,
devtool: 'eval-cheap-source-map',
module: {
rules: [
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object], [Object],
[Object]
]
},
resolve: {
extensions: [ '.mjs', '.js', '.ts' ],
alias: { vue: 'vue/dist/vue.common.js' }
},
plugins: [
DefinePlugin { definitions: [Object] },
ForkTsCheckerWebpackPlugin { options: [Object] },
],
optimization: { minimize: false, emitOnErrors: true }
}
我使用的是webpack 5.xx,但是使用4.xx时也遇到了同样的问题
我的TypeScript配置:
{
"compilerOptions": {
"target": "es2017",
"strict": true,
"module": "CommonJS",
"moduleResolution": "node",
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"allowJs": false,
"experimentalDecorators": true,
"baseUrl": "./",
"paths": {
},
"noUnusedParameters": true,
"noImplicitReturns": true
}
}
不满足动态加载的哪些条件?
你当前正在使用module: "CommonJS"
inside tsconfig.json
,这将导致所有动态在Webpack实际看到它们之前import()
被转换为require()
调用。为了使Webpack能够生成新的块,Webpack必须查看动态import()
调用。
设置module: "esnext"
将使之import()
不会动态转换成require()
,因此Webpack可以正确处理它们。
谢谢您的回答!我答应了你的奖赏^ _〜