Angular 12 import json into ts
Asked Answered
N

3

15

I have a json file into src/assets/version.json with this content:

{"VERSION":"1.0.0"}

and I import the file into the *.ts, eg.:

import * as VersionInfo from 'src/assets/version.json';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

 constructor() {
   console.log(`version ${VersionInfo['VERSION']}`);
 }

}

output

version 1.0.0

This works on Angular 11 but on Angular 12 the CLI show the error

Should not import the named export 'VERSION' (imported as 'VersionInfo') from default-exporting module (only default export is available soon)

this is my tsconfig.base.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "strictPropertyInitialization": false,
    "baseUrl": "./",
    "importHelpers": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "noImplicitAny": false,
    "target": "es2015",
    "resolveJsonModule": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ],
    "paths": {
      "jszip": [
        "node_modules/jszip/dist/jszip.min.js"
      ]
    }
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictTemplates": true,
    "strictInjectionParameters": true
  },
}

How fix this error?

Nidifugous answered 17/5, 2021 at 15:41 Comment(0)
S
22

Following should be placed in tsconfig.json

{
 ...
 "compilerOptions": {
    ...
    "resolveJsonModule": true, //already there
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true // Add this line
    ...
   },
...
}

and then simply import the following in your component

import VersionInfo from 'src/assets/version.json';
Selfdenial answered 17/5, 2021 at 17:56 Comment(2)
allowSyntheticDefaultImports should be inside compilerOptionsEverlasting
@Everlasting is correct about 'allowSyntheticDefaultImports' placement. Also, 'esModuleInterop' is not necessary to add.Athalie
T
7

You can try in the tsconfig.json as:

"compilerOptions": { "allowSyntheticDefaultImports":true }

And import:

import VersionInfo from 'src/assets/version.json';
Troytroyer answered 17/5, 2021 at 16:53 Comment(1)
Of all answers, this is only entirely correct oneAthalie
M
7

import { default as VersionInfo } from 'src/assets/version.json';

You need the two tsconfig entries mentioned above too.

Mella answered 17/5, 2021 at 22:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.