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.

Kay
  • 17,906
  • 63
  • 162
  • 270
  • 1
    try this: https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this – optimus Aug 23 '18 at 09: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? – Thomas Lee Dec 07 '18 at 01:59

1 Answers1

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).

Fabian
  • 86
  • 2