[英]Typescript compiler error when importing json file
所以代码很简单:
调用.json
{"SERVER":{
"requests":{
"one":"1"
}
} }
文件.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;
}
这显然会抛出:“环境模块声明不能指定相对模块名称”。
我还尝试了不同的变体,例如:
declare module 'calls.json' {
import * as json from '/private/static/calls.json';
export = json;
}
然后要求:
import json = require('calls.json');
没有一个可以正常工作,并且有自己的小编译器错误:)
我想使用外部 .json 文件,因为我使用 commonjs 服务器端和 amd 客户端,并且我想要一个用于加载常量的文件。
使用var
而不是import
。
var json = require('./calls.json');
您正在加载JSON文件,而不是模块,因此在这种情况下不应使用import
。 当使用var
, require()
再次被视为普通函数。
如果您正在使用Node.js定义,那么一切都应该正常工作,否则require
定义。
另一种解决方案是将data.json
更改为data.ts
并像这样导出
export default {
"key" : {
...
}
}
并按照您的预期导入:
import { default as data } from './data'
如果使用已经用json-loader打包的webpack v2 , 也可以使用import
语句来完成。
请注意,这不是异步
import data from './data.json';//Note that this is not async
另外,在你的typings.d.ts
文件中添加以下通配符模块以避免打字稿错误说: Cannot find module
declare module "*.json" {
const value: any;
export default value;
}
TS 2.9 增加了对良好类型的json导入的支持 。 只需添加:
{
"compilerOptions": {
"resolveJsonModule": true
}
}
在你的tsconfig.json
或jsconfig.json
。 现在进口如下:
import json = require('../static/calls.json');
和
import * as json from '../static/calls.json';
应该解决并有适当的打字!
从Typescript 2.9开始,您可以本机导入JSON文件,而无需任何额外的hack / loader。
以下摘录从上述链接复制而来。
...当使用moduleResolution的节点策略时,TypeScript现在能够将JSON文件作为输入文件导入。 这意味着你可以使用json文件作为他们项目的一部分,他们将是良好的类型!
./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`
2021 年。 我想导入 package.json 版本
对于 Angular 的人来说,如果你被卡住了。 想使用进口?
打开 tsconfig.json 并在compilerOptions键中添加
"resolveJsonModule": true,
就是这样你可以使用它
import { version } from '../package.json';
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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.