首页 > 解决方案 > 如何在 Angular 12 中读取本地 JSON 文件?

问题描述

我正在尝试从本地 JSON 文件中读取数据,该文件存储了我的应用程序的一些配置数据。ng build 在 Angular CLI 中使用命令时,我不断收到错误消息。

我的组件的 TypeScript 文件:my-component.ts

...
import credentials from './config/credentials.json';

export class MyComponent implements OnInit {
    ...
    // Properties
    username: string = credentials.username;
    ...
}

JSON 配置文件,存储在“/config”位置:credentials.json

{
    "credentials" : {
        "username" : "my_user_name",
        ...
    }
}

我收到错误消息:Error: Should not import the named export 'credentials' (imported as 'credentials') from default-exporting module (only default export is available soon)

是什么导致了这个错误?它似乎与此处描述的问题相似。

标签: javascriptjsonangulartypescript

解决方案


对于 Angular 版本 12,您还需要做两件事。

首先,您需要在文件中添加一些行。在这里参考这个问题。注意:这些不同于 Angular 版本 11。

{
    ...
        "compilerOptions": {
            ...
            "resolveJsonModule": true, // add this line...
            "esModuleInterop": true, // this line...
            ...
        },
    ...
    "allowSyntheticDefaultImports": true // and this line, notice this one is outside of "compiler options"
}

其次,您需要添加一个let语句。以上对我来说并不适用,但通过这一步,我让它工作了。参考这篇博文

我的组件的 TypeScript 文件:my-component.ts

...
import credentials from './config/credentials.json';

let my_username = credentials.username;  // ADD THIS LINE

export class MyComponent implements OnInit {
    ...
    // Properties
    username: string = my_username; // NOW USE THE NEW VARIABLE
    ...
}

诚然,我不完全理解为什么会这样,但它确实有效。该来源似乎表明它与变量范围有关。


推荐阅读