Error: *.default is not a constructor

Error: *.default is not a constructor

我在测试从打字稿文件转译的 javascript 代码时出现以下错误。

这是错误:

Error: _mapAction2.default is not a constructor

这是导致错误的代码行:

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

这是原始的打字稿文件map-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 文件 map-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

您需要导出一个 默认 值,它看起来像:

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

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

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

import LatLngLiteral from '';

import { LatLngLiteral } from '';

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

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

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

这是适合我的方式

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

如果您已经尝试过此处的答案但它们没有帮助,请仔细验证错误的堆栈跟踪 - 我在我的代码中发现了循环依赖(但错误与此问题中的错误相同,所以原因绝对不明显)