4

I am trying to import a .json file into a typescript file in angular.

import * as languagesData from './../../data/languages.json';

The above import statement gives the following error:

untouchable-app/library/data/languages"' resolves to a non-module entity and cannot be imported using this construct.

Folder structure.

library/
projects/
node_modules/
tsconfig.json
typings.d.ts

I have updated to typescript version 2.9.2

package.json

"devDependencies": {
    "typescript": "^2.9.2"
}

typings.d.ts

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

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "es2015",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "resolveJsonModule": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ],
    "paths": {
      "library": [
        "library/"
      ],
      "library/*": [
        "library/*"
      ]
    }
  }
}

library/services/report/report.service.ts

import * as languagesData from './../../data/languages.json';

projects/project-name/src/app/app.component.ts

import { ReportService } from 'library/services/report/report.service';

Note

I have a "library" folder which contains common components and services that can be shared across multiple apps contained in my projects folder. I am importing a service from the library into my application. The service file is the one that contains the import statement to the json data.

2
  • 1
    try this: stackoverflow.com/questions/39415661/… Commented Aug 23, 2018 at 9:51
  • does it work in your case using the tsconfig? I have tried, it doesn't work in my project. Do you have any update about this? Commented Dec 7, 2018 at 1:59

1 Answer 1

4

Try adding following to your tsconfig.json:

  "compilerOptions": {
     ...
     "esModuleInterop": true,
     ...
  }

And then import your json files this way:

import languagesData from './../../data/languages.json';

This worked for me (Angular 6, with angular cli).

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

Comments

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.