使用 Angular 导入本地 json 文件



我在项目之外有一个简单的.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 文件?

如果您使用的是 Typescript 2.9+ (Angular 6.1+(,则可以导入 JSON 模块,以便将其编译到应用程序中。旧版本不支持此功能,因此这可能是您的问题。

您需要做的就是确保在tsconfig.json中启用了以下三个编译器选项:

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

然后,您可以在任何 TS 文件中导入 JSON 模块:

import jsonContents from '../../contents.json';

尝试使用http调用:

this.http.get(`yourpath/..../common/configuration.json`).subscribe((resp: any) => {
console.log(resp)
});

我不太确定你的意思,但我想你想在你的组件中使用配置值,对吧?

根据本教程,可以通过在应用根文件夹中创建包含以下内容的类型定义文件json-typings.d.ts来解决此问题:

declare module "*.json" {
const value: any;
export default value;
}

最新更新