首页 文章

导入json文件时,Typescript编译器错误

提问于
浏览
44

所以代码很简单:

calls.json

{"SERVER":{
    "requests":{
      "one":"1"
    }
} }

file.ts

import json = require('../static/calls.json');
console.log(json.SERVER);

生成的javascript是正确的,当运行节点js服务器时,控制台日志json.SERVER打印'{requests:{one:'1'}}',就像它应该的那样 .

但是,打字稿编译器(commonjs)在某种程度上并不特别喜欢这种情况并抛出:“无法找到模块'../static/calls.json'” .

当然我试着写一个.d.ts文件,像这样:

declare module '../static/calls.json'{
    var exp:any;
    export = exp;
}

这显然会抛出:“Ambient模块声明不能指定相对模块名称” .

我也尝试了不同的变体,例如:

declare module 'calls.json' {
    import * as json from '/private/static/calls.json';
    export = json;
}

然后要求:

import json = require('calls.json');

没有正常工作,并有自己的小编译器错误:)

我想使用外部.json文件,因为我使用commonjs serverside和amd clientside,我想要一个文件来加载常量 .

6 回答

  • -2

    TS 2.9 added support for well typed json imports . 只需添加:

    {
      "compilerOptions": {
        "resolveJsonModule": true
      }
    }
    

    在你的 tsconfig.jsonjsconfig.json . 现在进口如下:

    import json = require('../static/calls.json');
    

    import * as json from '../static/calls.json';
    

    应该解决并有适当的打字!

  • 2
    For Angular 6 it can work with simple HTTP get call as below
    
    Service
    //interface, could be Array , object 
    export interface ResultJSON{
    
    }
     //Read JSON file for 3DWide
      getJSON() {
        return this.http.get(this.filepathUrl);
      }
    
    Component :import both service and interface and use as below
    resultJSON :ResultJSON;
     this
          .testService
          .getJSON()
          .subscribe((data: ResultJSON) => {
               this.resultJSON= data;
               console.log(this.resultJSON); 
    
    
             });
    
  • 20

    另一个解决方案是将 data.json 更改为 data.ts 并像这样导出

    export default {
      "key" : {
        ...
      }
    }
    

    并按预期导入:

    import { default as data } from './data'
    
  • 13

    如果使用已经用json-loader打包的webpack v2,也可以使用 import 语句来完成此操作 .

    请注意,这不是异步

    import data from './data.json';//Note that this is not async
    

    另外,在 typings.d.ts 文件中添加以下wildcard module以避免打字稿错误说: Cannot find module

    declare module "*.json" {
        const value: any;
        export default value;
    }
    

    对于对 async 进口感兴趣的任何人,请检查this article by 2uality

  • 18

    Typescript 2.9开始,您可以本机导入JSON文件,而无需任何额外的hack / loader .

    以下摘录从上述链接复制而来 .

    ...当使用moduleResolution的节点策略时,TypeScript现在能够将JSON文件作为输入文件导入 . 这意味着你可以使用json文件作为他们项目的一部分,他们将是良好的类型!

    ./src/settings.json

    {
        "dry": false,
        "debug":
    

    ./src/foo.ts

    import settings from "./settings.json";
    
    settings.debug === true;  // Okay
    settings.dry === 2;       // Error! Can't compare a `boolean` and `number`
    
  • 69

    使用 var 而不是 import .

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

    您正在加载JSON文件,而不是模块,因此在这种情况下不应使用 import . 使用 var 时, require() 再次被视为普通函数 .

    如果您正在使用Node.js定义,那么一切都应该正常工作,否则需要定义 require .

相关问题