Javascript 导入json文件时打字稿编译器错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32950966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:25:06  来源:igfitidea点击:

Typescript compiler error when importing json file

javascriptjsonnode.jstypescriptcommonjs

提问by Ken

So the code is simple:

所以代码很简单:

calls.json

调用.json

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

file.ts

文件.ts

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

the generated javascript is correct and when running the node js server, the console log json.SERVER prints '{ requests: { one: '1' } }', as it should.

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

The typescript compiler (commonjs) however, somehow does not particularly like this situation and throws: "Cannot find module '../static/calls.json'".

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

Ofcourse I tried writing a .d.ts file, like this:

当然,我尝试编写一个 .d.ts 文件,如下所示:

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

this then obviously throws: "Ambient module declaration cannot specify relative module name".

这显然会抛出:“环境模块声明不能指定相对模块名称”。

I also tried different variants, like:

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

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

and then requiring:

然后要求:

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

None work properly and have their own little compiler errors :)

没有一个可以正常工作,并且有自己的小编译器错误:)

I want to use an external .json file because I use commonjs serverside and amd clientside and I want a single file for loading constants.

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

回答by thoughtrepo

Use varinstead of import.

使用var代替import

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

You're loading a JSON file, not a module, so importshouldn't be used is this case. When varis used, require()is treated like a normal function again.

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

If you're using a Node.js definition, everything should just work, otherwise requirewill need to be defined.

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

回答by kenju

Another solution is to change data.jsonto data.tsand export like this

另一种解决方案是改变data.jsondata.ts出口是这样

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

and import as you would expect:

并按您的预期导入:

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

回答by sabithpocker

This can alsobe done by using importstatement if using webpack v2which is already packed with json-loader.

可以通过使用完成import,如果使用语句的WebPack V2这已经是挤满了JSON-装载机

Note that this is not async

请注意,这不是异步的

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

Also, in your typings.d.tsfile add the following wildcard moduleto avoid typescript error saying: Cannot find module

此外,在您的typings.d.ts文件中添加以下通配符模块以避免打字稿错误:Cannot find module

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

For anyone interested in asyncimports, check this article by 2uality

对于任何对async进口感兴趣的人,请通过 2uality查看这篇文章

回答by Matt Bierner

TS 2.9 added support for well typed json imports. Just add:

TS 2.9添加了对类型良好的 json 导入的支持。只需添加:

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

in your tsconfig.jsonor jsconfig.json. Now imports such as:

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

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

and

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

should be resolved and have proper typings too!

应该解决并有正确的打字!

回答by doomleika

As of Typescript 2.9you can import JSON file natively without any additional hack/loader needed.

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

The following excerpt is copied from said link above.

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

...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!

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

./src/settings.json

./src/settings.json

{
    "dry": false,
    "debug": 

./src/foo.ts

./src/foo.ts

import settings from "./settings.json";

settings.debug === true;  // Okay
settings.dry === 2;       // Error! Can't compare a `boolean` and `number`

回答by user2112373

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


         });