Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import JSON in Angular 7 project

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?

like image 349
Thomas Avatar asked Oct 19 '18 08:10

Thomas


1 Answers

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.

like image 189
Thomas Avatar answered Sep 20 '22 05:09

Thomas