[英]how to use a json file in a typescript file
I have a file called men.json. 我有一个名为men.json的文件。
I want to do the equivalent of var men = require('./men.json');
我想做相当于
var men = require('./men.json');
. 。
Whatever I have tried it looks for ./men.json.js
file. 无论我尝试过什么,它都会查找
./men.json.js
文件。
I read that I can not use import
since it is not a ts
file. 我读到我不能使用
import
因为它不是ts
文件。
What is the equivalent required line? 什么是等效的要求线?
declare module '*.json' {
var _: any;
export default _;
}
then you can import mem from './mem.josn'
然后你可以
import mem from './mem.josn'
put this into some file that's included in tsconfig.json
把它放到
tsconfig.json
包含的一些文件中
now you can require .json
, this works for any other file formats (though you need webpack since nodejs cannot require them directly) 现在你可以要求
.json
,这适用于任何其他文件格式(虽然你需要webpack,因为nodejs不能直接要求它们)
You should try requiring as follows: 你应该尝试如下要求:
// foo.ts
var mem = require('./mem.json);
console.log(mem);
Then compile ... 然后编译......
tsc foo.ts
This will give a generic typescript error, like: 这将给出一个通用的打字稿错误,如:
error TS2304: Cannot find name 'require
错误TS2304:找不到名称'require
which you could ignore ... or preferably, get rid of by installing the necessary typings - or package if you are using typescript 2 or later. 您可以忽略...或者最好通过安装必要的打字来摆脱 - 或者如果您使用打字稿2或更高版本打包。 (see typescript getting error TS2304: cannot find name ' require' )
(参见打字稿获取错误TS2304:找不到名称'require' )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.