【问题标题】:Error: *.default is not a constructor错误:*.default 不是构造函数
【发布时间】:2017-07-27 21:42:45
【问题描述】:

在测试一些从打字稿文件转译的 javascript 代码时,我收到以下错误。

这是错误:

Error: _mapAction2.default is not a constructor

这是导致错误的代码行:

var mapAction = new MapAction(MapActionType.POLYGONDRAGGED, []);

这是原始的打字稿文件ma​​p-action.ts

import { IMapAction} from './imap-action';
import { MapActionType } from './map-action-type.enum';
import {LatLngLiteral} from 'angular2-google-maps/core';

export class MapAction implements IMapAction{
    type: MapActionType;
    paths: Array<LatLngLiteral>;

    constructor(mapActionType: MapActionType, paths: Array<LatLngLiteral>){
        this.type = mapActionType;
        this.paths = paths;
    }

    public getType(): MapActionType{
        return this.type;
    }

    public getPaths(): Array<LatLngLiteral>
    {
        return this.paths;
    }

}

这是转译后的 .js 文件 ma​​p-action.js

"use strict";
class MapAction {
    constructor(mapActionType, paths) {
        this.type = mapActionType;
        this.paths = paths;
    }
    getType() {
        return this.type;
    }
    getPaths() {
        return this.paths;
    }
}
exports.MapAction = MapAction;
//# sourceMappingURL=map-action.js.map

【问题讨论】:

    标签: javascript typescript ava


    【解决方案1】:

    您需要导出一个 默认 值,如下所示:

    export default class MapAction implements IMapAction {...
    

    并将其导入为:

    import MapAction from './map_action_file';
    

    或者,如果您想从模块中导出 多个 内容,您可以执行以下操作:

    export class MapAction ...
    export class MapSomethng ...
    

    并按如下方式导入:

    import { MapAction, MapSomething } from './map_action_file';
    

    【讨论】:

    • 或者,import {MapAction} from './map_action_file' 不导出默认值
    • 谢谢你,我将所有与map_action相关的文件合并为一个,然后@Ksygo的评论修复了错误!
    • 缺少 {} 让我如此:import { Frak } from './Frak'; 修复了它。谢谢。
    【解决方案2】:

    检查您的导入是否正确。例如,您可能会错过 {}。

    import LatLngLiteral from '';
    

    import { LatLngLiteral } from '';
    

    【讨论】:

    • 你是救生员!
    • 天哪,这为我节省了很多时间。谢谢
    【解决方案3】:

    另一种解决方案是将"esModuleInterop": true, 添加到tsconfig.json

    esModuleInterop 允许从没有默认导出的模块进行默认导入。

    【讨论】:

    • 对我来说,使用 twitter-lite SDK 库时就是这种情况,因此其他用户可能会觉得它有帮助
    • 我已经知道了,但问题仍然存在。有什么想法吗?
    【解决方案4】:

    我在使用 node JS 和 mongoDB 时遇到了这个问题。问题出在我导入用户模型的方式上。

    这就是我的工作方式

    import { User } from '../models/User'
    

    【讨论】:

    【解决方案5】:

    由于 javascript are syntactic sugar 中的类,我想我会尝试在没有它们的情况下解决这个问题。对我来说,将架构切换到原型似乎已经解决了我的问题。发帖以防其他人遇到此问题但已经在做export default

    【讨论】:

    • 这实际上并没有给出如何解决实际问题的最简单的提示。我认为您建议他应该重写导入的模块以不使用类(但我可能大错特错......)。虽然也许 OP可以做到这一点,但大多数带着同样问题来到这里的人将要处理他们无法修改的第三方模块。
    猜你喜欢
    • 2022-06-11
    • 2020-03-30
    • 2021-06-20
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 1970-01-01
    相关资源
    最近更新 更多