Import a JSON file into a node application using TypeScript

I'm really going crazy because I can’t find a solution for this. I want to archive in order to import the configuration JSON file into my TypeScript file. I found out that I need a declaration file. So I added the json-loader.d.ts file to my project. I also tried it on several levels (root, typings folder, custom_typings folder) because these are the solutions that I found. The contents of the file are as follows:

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 a JSON file because it is not a module. So how does the compiler know that there is such a declaration file?

I already tried changing my tsconfig.json as follows:

 { "compilerOptions": { "target": "es6", "module": "commonjs", "outDir": "dist", "typeRoots": [ "./node_modules/@types", "./typings" ] }, "include": [ "src/**/*.ts" ], "exclude": [ "node_modules" ] } 

But that still doesn't work. Any suggestions?

Thanks!

+3
typescript typescript-typings
source share
2 answers

Online examples using declare module "*.json" work because Webpack is configured to download JSON files.

If you don't want to worry about this, you can use var instead of import :

var json = require('../config.json');

as suggested in this answer

+4
source share

You did something like adding a SystemJS script to your webpage to load the module - index.html, etc. I used https://cdnjs.com/libraries/systemjs and iirc you need https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.20.14/system.src.js System.JS is the module loader. Must be the first script imported. And then you need something like this:

  <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.20.14/system.src.js "/> <script> System.config({ defaultJSExtension:true }); System.import('pathtoscriptwithoutdotjsatend'); </script> 
0
source share

All Articles