我在项目外有一个简单的.json
文件。像这样:
| common
| configuration.json
| angular-app
| src
| app
| my-component
| my-component.component.ts
| angular.json
在my-component.component.ts
中,我要导入configuration.json
。我尝试了import configuration from '../../../../common.configuration.json'
,但Angular一直抛出此错误:
ERROR in src/app/record/record.component.ts(4,23): error TS2732: Cannot find module '../../../../common/configuration.json'. Consider using '--resolveJsonModule' to import module with '.json' extension
当我尝试ng serve --resolveJsonModule
时,出现此错误:Unknown option: '--resolveJsonModule'
我无法移动configuration.json
。 common
目录与其他项目共享。
如何在Angular项目中导入本地json文件?
答案 0 :(得分:1)
如果您使用的是2.9版或更高版本的打字稿(Angular 6.1+),则可以导入JSON模块,以便将其编译到应用程序中。旧版本不支持此功能,因此可能是您的问题。
您需要做的就是确保在tsconfig.json中启用了以下三个编译器选项:
{
...
"compilerOptions": {
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
...
}
}
然后,您可以在任何TS文件中导入JSON模块:
import jsonContents from '../../contents.json';
答案 1 :(得分:0)
尝试使用 http 呼叫:
this.http.get(`yourpath/..../common/configuration.json`).subscribe((resp: any) => {
console.log(resp)
});
答案 2 :(得分:0)
我不确定您的意思,但我想您想在组件中使用配置值,对吧?
根据此tutorial,可以通过在应用程序根文件夹中创建具有以下内容的类型定义文件json-typings.d.ts
来解决此问题:
declare module "*.json" {
const value: any;
export default value;
}