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

Typescript compiler error when importing json file

所以代码很简单:

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' } }',作为应该。

然而,typescript 编译器 (commonjs) 并不特别喜欢这种情况并抛出:"Cannot find module '../static/calls.json'".

当然我试过写一个 .d.ts 文件,像这样:

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

这显然会抛出:"Ambient module declaration cannot specify relative module name".

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

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

然后要求:

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

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

我想使用外部 .json 文件,因为我使用 commonjs 服务器端和 amd 客户端,我想要一个文件来加载常量。

使用 var 而不是 import

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

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

如果您使用的是 Node.js 定义,则一切正常,否则需要定义 require

如果使用 webpack v2 which is already packed with json-loader.

,这可以 通过使用 import 语句来完成

Note that this is not async

import data from './data.json';//Note that this is not async

此外,在您的 typings.d.ts 文件中添加以下内容 wildcard module 以避免打字稿错误提示:Cannot find module

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

任何对 async 导入感兴趣的人,请查看 this article by 2uality

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

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

并按照您的预期导入:

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

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';

应该得到解决并且也有正确的打字!

Typescript 2.9 开始,您可以本地导入 JSON 文件,无需任何额外的 hack/loader。

以下摘录自上述link。

...TypeScript is now able to import JSON files as input files when using the node strategy for moduleResolution. This means you can use json files as part of their project, and they’ll be well-typed!

./src/settings.json

{
    "dry": false,
    "debug": 

./src/foo.ts

import settings from "./settings.json";

settings.debug === true;  // Okay
settings.dry === 2;       // Error! Can't compare a `boolean` and `number`
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); 


         });

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

致 Angular 人,如果你遇到困难。想要使用导入?

打开tsconfig.json & 在里面添加compilerOptions key

"resolveJsonModule": true,

就是这样你可以使用它

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