导入json文件时,Typescript编译器错误 [英] Typescript compiler error when importing json file
问题描述
所以代码很简单:
calls.json
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'}}',应该如此。
the generated javascript is correct and when running the node js server, the console log json.SERVER prints '{ requests: { one: '1' } }', as it should.
打字稿编译器(commonjs)然而,不知何故,并不特别喜欢这种情况并抛出: 找不到模块'../ static / calls.json'。
The typescript compiler (commonjs) however, somehow does not particularly like this situation and throws: "Cannot find module '../static/calls.json'".
当然我尝试写一个.d.ts文件,如下所示:
Ofcourse I tried writing a .d.ts file, like this:
declare module '../static/calls.json'{
var exp:any;
export = exp;
}
这显然会抛出:Ambient模块声明不能指定相对模块名称。
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;
}
然后要求:
import json = require('calls.json');
没有正常工作并且有自己的小编译错误:))
None work properly and have their own little compiler errors :)
我想使用外部.json文件,因为我使用commonjs serverside和amd clientside,我想要一个文件来加载常量。
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.
推荐答案
使用 var
而不是 import
。
var json = require('./calls.json');
您正在加载JSON文件,而不是模块,因此 import <在这种情况下不应该使用/ code>。当使用
var
时, require()
将被视为普通函数。
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.
如果您使用的是Node.js定义,那么一切都应该正常工作,否则需要定义 require
。
If you're using a Node.js definition, everything should just work, otherwise require
will need to be defined.
这篇关于导入json文件时,Typescript编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!