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;
}
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?
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?
Thanks!
The TypeScript comes up with the functionality of working with JSON Type data. JSON being the JavaScript Object Notation, is used to make a data model that is easy to write and read. We can easily analyze large and complex data set with this TypeScript JSON type.
We can read this JSON data in JavaScript using the import statement this way: <! ---./index. js--> import data from './data.
Examples on the web that use declare module "*.json"
work because Webpack is configured to load JSON files.
If you don't want to bother with that you can use var
instead of import
:
var json = require('../config.json');
as suggested in this answer
I've successfully used the following to import my package.json
inside a CLI program (so I can re-use the version, license and description information in my help page).
declare module '*.json' {
const foo: {
name: string;
version: string;
author: string;
license: string;
description: string;
};
export = foo;
}
Alternatively, you can import other files containing interface descriptions etc., but you need to put the imports inside the module declaration, e.g.
declare module 'ormconfig.json' {
import { Connection } from "typeorm";
const foo: Connection[];
export = foo;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With