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

问题描述 投票:51回答:6

所以代码很简单:

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,我想要一个文件来加载常量。

javascript json node.js typescript commonjs
6个回答
75
投票

使用var而不是import

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

您正在加载JSON文件,而不是模块,因此在这种情况下不应使用import。当使用var时,require()再次被视为正常功能。

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


24
投票

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

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

并按照您的预期导入:

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

20
投票

如果使用已经装有importwebpack v2,也可以使用json-loader语句来完成。

请注意,这不是异步

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


14
投票

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
投票

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`

-4
投票
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); 


         });
© www.soinside.com 2019 - 2024. All rights reserved.