You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular 16中启用Top-Level Await?解决模块解析报错

在Angular 16中启用Top-Level Await解决模块解析错误

错误根源在于依赖包lucid-cardano使用了顶层await特性,而Angular默认封装的Webpack配置未开启该实验选项。仅修改angular.json和tsconfig无法生效,需要通过自定义Webpack配置来开启。

解决步骤:

  1. 安装自定义Webpack构建工具
    执行以下命令安装依赖:

    npm install @angular-builders/custom-webpack --save-dev
    
  2. 创建Webpack配置文件
    在项目根目录新建webpack.config.js,写入以下内容:

    module.exports = {
      experiments: {
        topLevelAwait: true
      }
    };
    
  3. 修改Angular构建配置
    打开angular.json,找到architect下的build和serve节点:

    • 将builder字段分别替换为@angular-builders/custom-webpack:browser(build)和@angular-builders/custom-webpack:dev-server(serve)
    • 在对应的options中添加自定义Webpack配置路径:
      "build": {
        "builder": "@angular-builders/custom-webpack:browser",
        "options": {
          "customWebpackConfig": {
            "path": "./webpack.config.js"
          },
          // 保留原有其他配置...
        }
      },
      "serve": {
        "builder": "@angular-builders/custom-webpack:dev-server",
        "options": {
          "customWebpackConfig": {
            "path": "./webpack.config.js"
          },
          // 保留原有其他配置...
        }
      }
      
  4. 检查TypeScript配置
    确保tsconfig.json的compilerOptions中target设置为ES2022或更高版本:

    {
      "compilerOptions": {
        "target": "ES2022",
        // 其他配置...
      }
    }
    
  5. 验证修复效果
    重启开发服务器或重新构建项目:

    ng serve
    # 或
    ng build
    

内容的提问来源于stack exchange,提问作者Emmanuel Mutisya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:27:17