如何在Angular 16中启用Top-Level Await?解决模块解析报错
在Angular 16中启用Top-Level Await解决模块解析错误
错误根源在于依赖包lucid-cardano使用了顶层await特性,而Angular默认封装的Webpack配置未开启该实验选项。仅修改angular.json和tsconfig无法生效,需要通过自定义Webpack配置来开启。
解决步骤:
安装自定义Webpack构建工具
执行以下命令安装依赖:npm install @angular-builders/custom-webpack --save-dev创建Webpack配置文件
在项目根目录新建webpack.config.js,写入以下内容:module.exports = { experiments: { topLevelAwait: true } };修改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" }, // 保留原有其他配置... } }
- 将
检查TypeScript配置
确保tsconfig.json的compilerOptions中target设置为ES2022或更高版本:{ "compilerOptions": { "target": "ES2022", // 其他配置... } }验证修复效果
重启开发服务器或重新构建项目:ng serve # 或 ng build
内容的提问来源于stack exchange,提问作者Emmanuel Mutisya
相关产品推荐
相关产品推荐

