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
Typescript compiler error when importing json file
提问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 var
instead of import
.
使用var
代替import
。
var json = require('./calls.json');
You're loading a JSON file, not a module, so import
shouldn't be used is this case. When var
is 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 require
will need to be defined.
如果您使用 Node.js 定义,一切都应该正常工作,否则require
需要定义。
回答by kenju
Another solution is to change data.json
to data.ts
and export like this
另一种解决方案是改变data.json
对data.ts
出口是这样
export default {
"key" : {
...
}
}
and import as you would expect:
并按您的预期导入:
import { default as data } from './data'
回答by sabithpocker
This can alsobe done by using import
statement 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.ts
file 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 async
imports, 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.json
or jsconfig.json
. Now imports such as:
在您的tsconfig.json
或jsconfig.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);
});