【问题标题】:Importing json file into angular 4.x TypeScript application将 json 文件导入 Angular 4.x TypeScript 应用程序
【发布时间】:2018-11-14 20:43:52
【问题描述】:

假设我有以下 json 文件(角度应用程序的根):

{
   "propertyName": "ABC"
}

我知道 TypeScript 不能直接处理 JSON 导入,所以我根据 TypeScript 模块文档使用通配符 (typings.d.ts) 删除了以下模块:

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

现在我可以像这样导入本地 json 文件(上面的结构):

import * as config from './config.json';

之后我可以像这样使用导入的任何属性:

let propertyA: string = (<any>config).propertyName;

一切都很好,但是当我尝试使用时

let propertyA: string = config.propertyName;

我收到以下错误消息:

src/main.ts(9,26) 中的错误:错误 TS2339:属性“propertyName” 'typeof "*.json"' 类型上不存在。

任何建议如何在构建过程中避免此错误?该过程成功完成(包括此错误消息),我可以使用 Web 应用程序以及所需的属性。它只是生成一条错误消息

【问题讨论】:

标签: json angular typescript


【解决方案1】:

我遇到了类似的问题,因为它是一个 json 文件,没有模块,不需要编译,你可以像在 javascript 中一样导入它。

const config = require('./config.json');

此时访问配置属性不会有任何错误,并且仍然可以正常工作。

请记住,您可能需要导入 @types/node 包才能使用 require 方法。

【讨论】:

    猜你喜欢
    • 2017-12-28
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 2018-04-10
    • 1970-01-01
    • 2019-12-11
    • 2013-10-17
    相关资源
    最近更新 更多