Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import JSON file in node application with TypeScript

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!

like image 709
ppulwey Avatar asked Jul 05 '17 14:07

ppulwey


People also ask

Can you use JSON in TypeScript?

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.

Can we import JSON file in JavaScript?

We can read this JSON data in JavaScript using the import statement this way: <! ---./index. js--> import data from './data.


2 Answers

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

like image 170
tony Avatar answered Sep 29 '22 07:09

tony


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;
}
like image 31
Erik Vullings Avatar answered Sep 29 '22 07:09

Erik Vullings