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

导入ngsw-config.json时Angular构建报错:assetGroups.find未找到

Angular导入ngsw-config.json构建失败的解决办法

问题场景

在Angular组件中导入ngsw-config.json并读取其属性,执行ng build时构建失败。组件代码如下:

// app.component.ts
import * as ngswConfig from '../../ngsw-config.json';

ngOnInit() {
    console.log(ngswConfig.assetGroups.find(x => x.name === 'app'));
}

报错信息

./src/app/app.component.ts:55:18-45 - Error: export 'assetGroups'.'find' (imported as 'ngswConfig') was not found in '../../ngsw-config.json' (possible exports: 0, 1)

已尝试配置

在tsconfig.json的compilerOptions中添加了以下设置:

"resolveJsonModule": true,
"esModuleInterop": true,

环境信息

  • Angular版本:12、16
  • NodeJS版本:v20.9.0

解决方案

问题根源在于JSON文件的导入解析方式:开启esModuleInterop后,TypeScript会将JSON文件当作CommonJS模块处理,其内容会被包裹在default导出属性中,而非直接挂载在导入对象的根层级。

方案1:修改导入语句为默认导入

直接导入JSON的默认导出,可直接访问属性:

// app.component.ts
import ngswConfig from '../../ngsw-config.json';

ngOnInit() {
    console.log(ngswConfig.assetGroups.find(x => x.name === 'app'));
}

方案2:保留原导入方式,调整访问路径

如果坚持使用命名导入,需通过default属性访问JSON内容:

// app.component.ts
import * as ngswConfig from '../../ngsw-config.json';

ngOnInit() {
    console.log(ngswConfig.default.assetGroups.find(x => x.name === 'app'));
}

补充配置(可选)

在tsconfig.json中添加allowSyntheticDefaultImports,确保TypeScript允许对非ES模块使用默认导入:

{
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 21:55:01