所以代码很简单:
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,我想要一个文件来加载常量。
使用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'
如果使用已经装有import
的webpack v2,也可以使用json-loader语句来完成。
请注意,这不是异步
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
TS 2.9 added support for well typed json imports。只需添加:
{
"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`
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);
});