【问题标题】:How to import json file to be available in angular-cli npm test如何导入 json 文件以在 angular-cli npm test 中可用
【发布时间】:2017-06-23 12:56:44
【问题描述】:

给定带有 angular-cli(1.1.3 版)的 angular 版本 4.2.4 和以下代码:

import languagesJsonRaw from './languages/en.json';
import countriesJsonRaw from './countries/en.json';

export const languages = prepareLanguages(languagesJsonRaw);
export const countries = prepareCountries(countriesJsonRaw);

这在我运行 npm start(触发 ng serve)时有效 - languagescountries 可用于应用程序。

当我运行npm test 时,基本上会触发:

ng test --reporters dots,html --browsers Chrome --watch

那么languagesJsonRawcountriesJsonRaw 是未定义的。

如何将这些文件也提供给测试运行者?我认为我们不需要为他们做任何特别的事情就可以从ng serveng build 获得它们,甚至可以使用 AOT。

它是默认的 angular-cli 项目,所以我认为测试运行器是业力。

Github 问题https://github.com/angular/angular-cli/issues/6786

【问题讨论】:

  • 我从来没有像这样导入 json,我总是在 json 的路径上创建一个 http.get,我想它应该可以工作
  • 你好,这个问题你解决了吗?如果没有,请对您的代码提出建议,我认为您应该更改导入这些 json 文件的方式,例如: import * as json from './languages/en.json';... 也许它已经太晚了
  • 您可以查看 Kaloyan Kosev 的答案stackoverflow.com/a/44930845/3848632。我遇到了同样的问题,并且有效。

标签: angular typescript karma-runner angular-cli


【解决方案1】:

将以下代码附加到src/typings.d.ts

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

这将允许您加载.json 模块。

您可以在此处查看完整说明: https://hackernoon.com/import-json-into-typescript-8d465beded79

【讨论】:

  • 这并不能解决 npm test 的问题,试试看,不行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-04
  • 2017-04-19
  • 2017-03-07
  • 2019-09-01
  • 2017-09-16
  • 2018-05-24
  • 1970-01-01
相关资源
最近更新 更多