【问题标题】:importing js file into ts file将js文件导入ts文件
【发布时间】:2019-05-31 17:53:44
【问题描述】:

我已经阅读了几篇关于此的帖子。我的方法昨天有效,但今天失败了。我正在将 js 文件导入 ts 文件。 allowJstsconfig.json 中设置为true

得到以下错误:

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;

【问题讨论】:

    标签: javascript typescript import


    【解决方案1】:
    1. 在您的ecn-info.js 文件中使用export default
    export default class EcnInfo {
        constructor(name, structure, status) {
            this.name = name;
            this.structure = structure;
            this.status = status;
        }
    }
    
    1. 在您的tsconfig.json 中禁用noImplicitAny
    {
      "compilerOptions": {
        "noImplicitAny": false
        ...
      }
    }
    
    1. 像这样导入:
    import EcnInfo from '../../../../shared/models/ecn-info';
    

    更新

    这是一种不使用默认导出的方法:

    1. 在您的ecn-info.js 文件中使用export
    export class EcnInfo {
        constructor(name, structure, status) {
            this.name = name;
            this.structure = structure;
            this.status = status;
        }
    }
    
    1. 在您的tsconfig.json 中禁用noImplicitAny
    {
      "compilerOptions": {
        "noImplicitAny": false
        ...
      }
    }
    
    1. 像这样导入:
    import {EcnInfo} from '../../../../shared/models/ecn-info';
    

    【讨论】:

    • 感谢您的回答.. 尝试您的建议后:ERROR in app/core/input-parser.service.ts(5,8): error TS1192: Module '".../dashboard/shared/models/ecn-info"' has no default export.
    • 我在我的 sn-p 中为ecn-info.js 犯了一个错误。我更新了它 - 添加了 default 关键字。现在让我知道它是如何工作的。
    • 并且还添加了另一个选项——不使用默认导出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-11
    • 1970-01-01
    • 2017-10-31
    • 2018-10-10
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    相关资源
    最近更新 更多