导入json文件时,Typescript编译器错误

时间:2015-10-05 14:24:28

标签: javascript json node.js typescript commonjs

所以代码很简单:

calls.json

{"SERVER":{
    "requests":{
      "one":"1"
    }
} }

file.ts

import json = require('../static/calls.json');
console.log(json.SERVER);

生成的javascript是正确的,当运行节点js服务器时,控制台日志json.SERVER打印' {requests:{one:' 1'应该如此。

打字稿编译器(commonjs)然而,不知何故并不特别喜欢这种情况并抛出:"找不到模块' ../ static / calls.json'"。

当然我试着写一个.d.ts文件,如下:

declare module '../static/calls.json'{
    var exp:any;
    export = exp;
}

这显然会引发:" Ambient模块声明无法指定相关模块名称"。

我也尝试了不同的变体,例如:

declare module 'calls.json' {
    import * as json from '/private/static/calls.json';
    export = json;
}

然后要求:

import json = require('calls.json');

没有正常工作并且有自己的小编译器错误:)

我想使用外部.json文件,因为我使用commonjs serverside和amd clientside,我想要一个文件来加载常量。

6 个答案:

答案 0 :(得分:75)

使用var代替import

var json = require('./calls.json');

您正在加载JSON文件,而不是模块,因此在这种情况下不应使用import。使用var时,require()会被视为普通函数。

如果您使用的是Node.js定义,那么一切都应该正常工作,否则需要定义require

答案 1 :(得分:24)

另一个解决方案是将data.json更改为data.ts并像这样导出

export default {
  "key" : {
    ...
  }
}

并按预期导入:

import { default as data } from './data'

答案 2 :(得分:14)

TS 2.9 added support for well typed json imports。只需添加:

{
  "compilerOptions": {
    "resolveJsonModule": true
  }
}

在您的tsconfig.jsonjsconfig.json中。现在进口如:

import json = require('../static/calls.json');

import * as json from '../static/calls.json';

应该得到解决并且也有正确的类型!

答案 3 :(得分:2)

Typescript 2.9开始,您可以原生导入JSON文件,而无需任何额外的黑客/加载程序。

以下摘录是从上述链接中复制的。

  

...当使用moduleResolution的节点策略时,TypeScript现在能够将JSON文件作为输入文件导入。这意味着您可以将json文件用作其项目的一部分,并且它们的输入效果很好!

<div class="row" style="margin-top:3px"> <div class="col-lg-4"> @(Html.LabelFor(r => r.ReportDate)) </div> <div class="col-lg-8"> ${ReportDate} </div> </div>

./src/settings.json

{ "dry": false, "debug":

./src/foo.ts

答案 4 :(得分:0)

2021 年。 我想导入 package.json 版本

对于 Angular 的人,如果你被卡住了。要使用导入吗?

打开 tsconfig.json 并在 compilerOptions 键中添加

"resolveJsonModule": true,

这样就可以使用了

import { version } from '../package.json';

答案 5 :(得分:-4)

For Angular 6 it can work with simple HTTP get call as below

Service
//interface, could be Array , object 
export interface ResultJSON{

}
 //Read JSON file for 3DWide
  getJSON() {
    return this.http.get(this.filepathUrl);
  }

Component :import both service and interface and use as below
resultJSON :ResultJSON;
 this
      .testService
      .getJSON()
      .subscribe((data: ResultJSON) => {
           this.resultJSON= data;
           console.log(this.resultJSON); 


         });