Import JSON in Angular 7 project

Thomas picture Thomas · Oct 19, 2018 · Viewed 17.5k times · Source

In my Angular project I'm importing JSON files for my own little localization service. I'm using the method suggested here, updating my typings.d.ts to

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

This worked fine for Angular 6, but after the update to Angular 7 my imports seem to be undefined when I try to access a property.

import * as de from './strings/de.json';
import * as en from './strings/en.json';

var s = en["mykey"]

The JSON has a very simple key => value structure:

{
  "myKey": "My Headline",
  …
}

What has changed between 6.1 & 7 that could lead to this behaviour?

Answer

Thomas picture Thomas · Oct 19, 2018

Turns out with Angular 7 & TypeScript 3.1 there actually have been some changes (I guess they have been there since TS 2.9+?). Using the code in the question, all values are wrapped inside a 'default'-object. To prevent this I had to simplify the import statements:

import de from './strings/de.json';
import en from './strings/en.json';

Also see this question for more details on how to import JSON files in TypeScript.