首页 > 解决方案 > (Angular 12)目标环境不支持动态 import() 语法,因此无法在脚本中使用外部类型“模块”

问题描述

我有以下动态导入代码在运行时导入 js 库:

export class AuthService {
    constructor() {
        import('https://apis.google.com/js/platform.js').then(result => {
            console.log(result)
        })
    }
}

但是,当我尝试构建/服务 Angular 项目时,我得到:

external "https://apis.google.com/js/platform.js" - 错误:目标环境不支持动态 import() 语法,因此无法在脚本中使用外部类型“模块”您是说构建一个 EcmaScript 模块 ('output.module: true')?

此外,vs-code 突出显示import以下内容:
在此处输入图像描述

我尝试添加"type": "module"inpackage.json"module": "ESNext"in tsconfig.json,但没有运气。

我怎样才能解决这个问题?

标签: javascriptangulartypescriptwebpack

解决方案


Dynamic imports only works since ES2020. Please, check your tsconfig.json in order to know what version is your target.


推荐阅读