简体   繁体   中英

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;
  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';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM