3

Given angular version 4.2.4 with angular-cli (version 1.1.3) and following code:

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

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

This works when I run npm start (which triggers ng serve) - languages and countries are available to the application.

When I run npm test, which basically triggers:

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

then languagesJsonRaw and countriesJsonRaw are undefined.

How can I provide those files also to the test runner? I don't think we needed to do anything special for them to be available from ng serve or ng build, works even with AOT.

It's default angular-cli project, so test runner is karma I think.

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

3
  • I've never import json like that, I always make a http.get to the path of the json, I suppose it should work Commented Jun 23, 2017 at 14:50
  • Hey, did you sort out this problem? If not, got a suggestion for your code, I think you should change the way you do the imports of those json files, something like: import * as json from './languages/en.json';... maybe it's already too late Commented Nov 5, 2018 at 0:06
  • You can look at this answer stackoverflow.com/a/44930845/3848632 by Kaloyan Kosev. I had the same problem and that works. Commented Dec 18, 2018 at 16:21

1 Answer 1

2

Append the following code to src/typings.d.ts

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

This will allow you to load .json modules.

You can view a full explanation here: https://hackernoon.com/import-json-into-typescript-8d465beded79

Sign up to request clarification or add additional context in comments.

1 Comment

this doesn't solve the issue with npm test, try it out, it won't work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.