问题描述
我真的快疯了,因为我找不到解决方案.我想要存档的是将带有配置的 JSON 文件导入到我的 TypeScript 文件中.我了解到我需要一个声明文件.所以我在我的项目中添加了一个文件 json-loader.d.ts .我还在多个级别(根目录、typings 文件夹、custom_typings 文件夹)尝试了它,因为这是我找到的解决方案.文件内容如下所示:
I'm really getting crazy because I can't find a solution for this.What I want to archive is to import a JSON file with a configuration into my TypeScript file.I've learned that I need a declaration file. So I've added a file json-loader.d.ts into my project. I also tried it at several levels (root, typings folder, custom_typings folder) because this are the solutions I've found.The file content looks like this:
declare module "json!*" {
let json: any;
export = json;
}
declare module "*.json" {
const value: any;
export default value;
}
但是编译器仍然告诉我,无法导入 JSON 文件,因为它不是模块.那么,编译器是如何知道有这样一个声明文件的?
But the compiler still tells me, that it is not possible to import the JSON file, because it isn't a module.So, how is the compiler getting aware, that there is such a declaration file?
我已经尝试像这样修改我的 tsconfig.json:
I already tried to modify my tsconfig.json like this:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"outDir": "dist",
"typeRoots": [
"./node_modules/@types",
"./typings"
]
},
"include": [
"src/**/*.ts"
],
"exclude": [
"node_modules"
]
}
但是还是不行.有什么建议吗?
But it still doesn't work. Any suggestions?
谢谢!
推荐答案
网络上使用 declare module "*.json"
的示例可以工作,因为 Webpack 被配置为加载 JSON 文件.
Examples on the web that use declare module "*.json"
work because Webpack is configured to load JSON files.
如果您不想为此烦恼,您可以使用 var
而不是 import
:
If you don't want to bother with that you can use var
instead of import
:
var json = require('../config.json');
这篇关于使用 TypeScript 在节点应用程序中导入 JSON 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!