【问题标题】:Import JSON file in node application with TypeScript使用 TypeScript 在节点应用程序中导入 JSON 文件
【发布时间】:2017-12-09 06:53:35
【问题描述】:

我真的快疯了,因为我找不到解决方案。 我要归档的是将带有配置的 JSON 文件导入我的 TypeScript 文件。 我知道我需要一个声明文件。所以我在我的项目中添加了一个文件 json-loader.d.ts 。我还在多个级别(根目录、typings 文件夹、custom_typings 文件夹)尝试了它,因为这是我找到的解决方案。 文件内容如下:

declare module "json!*" {
    let json: any;
    export = json;
}

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

但编译器仍然告诉我,无法导入 JSON 文件,因为它不是模块。 那么,编译器是如何知道有这样一个声明文件的呢?

我已经尝试像这样修改我的 tsconfig.json:

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

但它仍然不起作用。有什么建议吗?

谢谢!

【问题讨论】:

  • 您能否展示一下您是如何尝试导入 json 的?
  • 我试过了:import * as config from '../config.json'。当 JSON 像我猜的模块一样处理时应该可以工作......
  • 以防有人偶然发现这个问题。对于 nodejs 应用程序,您可以使用 npmjs.com/package/load-json-file

标签: typescript typescript-typings


【解决方案1】:

Web 上使用 declare module "*.json" 的示例可以正常工作,因为 Webpack 被配置为加载 JSON 文件。

如果您不想为此烦恼,可以使用var 而不是import

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

as suggested in this answer

【讨论】:

  • 谢谢。这行得通。只是忘记运行将 .json 文件复制到 dist 目录的 gulp 任务... (ツ)
  • 这让我摆脱了编译错误,但在运行时我仍然收到Cannot find module 错误。注意:尝试将 json 导入 jasmine 规范文件
【解决方案2】:

我已成功使用以下内容在 CLI 程序中导入我的 package.json(因此我可以在帮助页面中重复使用版本、许可证和描述信息)。

declare module '*.json' {
  const foo: {
    name: string;
    version: string;
    author: string;
    license: string;
    description: string;
  };
  export = foo;
}

或者,您可以导入包含接口描述等的其他文件,但您需要将导入放在模块声明中,例如

declare module 'ormconfig.json' {
  import { Connection } from "typeorm";

  const foo: Connection[];
  export = foo;
}

【讨论】:

  • 你把上面的声明模块位,typings.d.ts 放在哪里了?
  • @ArsalanKhalid 作为单独的文件,例如ormconfig.d.ts 代码中的任何位置都应该没问题...我通常将它们添加到 utils 文件夹或 typings 文件夹(如果我有很多)。
【解决方案3】:

您是否做过类似在您的网页中添加 SystemJS 脚本来加载模块的操作 - index.html 等。我使用了 https://cdnjs.com/libraries/systemjs 和 iirc,您需要 https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.20.14/system.src.js System.JS 是模块加载器.. 必须是导入的第一个脚本。 然后你需要这样的东西:

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

【讨论】:

  • 这是一个节点应用程序。没有网页。应该提到它......对不起。
猜你喜欢
  • 2016-12-11
  • 2018-11-14
  • 2019-12-11
  • 2020-10-09
  • 1970-01-01
  • 2013-08-25
  • 2019-05-12
  • 2018-10-04
相关资源
最近更新 更多