Shi Zhang
Shi Zhang

Reputation: 163

importing js file into ts file

I've already read several posts concerning this. My approach was working yesterday but today it is failing. I'm importing a js file into a ts file. allowJs is set to true in tsconfig.json.

Getting the following error:

ERROR in src/app/core/input-parser.service.ts(5,26): error TS2497: Module '".../dashboard/shared/models/ecn-info"' resolves to a non-module entity and cannot be imported using this construct.

input-parser.service.ts:

import * as EcnInfo from '../../../../shared/models/ecn-info';

ecn-info.js:

class EcnInfo {
  constructor(name, structure, status) {
    this.name = name;
    this.structure = structure;
    this.status = status;
  }
}

module.exports = EcnInfo;

Upvotes: 0

Views: 6330

Answers (1)

JME
JME

Reputation: 503

  1. Use an export default in your ecn-info.js file:
export default class EcnInfo {
    constructor(name, structure, status) {
        this.name = name;
        this.structure = structure;
        this.status = status;
    }
}
  1. Disable noImplicitAny in your tsconfig.json:
{
  "compilerOptions": {
    "noImplicitAny": false
    ...
  }
}
  1. Import like this:
import EcnInfo from '../../../../shared/models/ecn-info';

Update

Here is an approach without using default export:

  1. Use an export in your ecn-info.js file:
export class EcnInfo {
    constructor(name, structure, status) {
        this.name = name;
        this.structure = structure;
        this.status = status;
    }
}
  1. Disable noImplicitAny in your tsconfig.json:
{
  "compilerOptions": {
    "noImplicitAny": false
    ...
  }
}
  1. Import like this:
import {EcnInfo} from '../../../../shared/models/ecn-info';

Upvotes: 1

Related Questions