Import JSON file in node application with TypeScript

前端 未结 3 862
故里飘歌
故里飘歌 2021-01-18 10:33

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 lear

相关标签:
3条回答
  • 2021-01-18 11:00

    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

    0 讨论(0)
  • 2021-01-18 11:08

    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;
    }

    0 讨论(0)
  • 2021-01-18 11:20

    Have you done something like add a SystemJS script in your web page to do module loading - 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.. Has to be 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 讨论(0)
提交回复
热议问题