错误:*.default不是构造函数

Chr*_*sen 40 javascript typescript ava

我在测试一些javascript代码时得到以下错误,从一个打字稿文件中转换而来.

这是错误:

Error: _mapAction2.default is not a constructor
Run Code Online (Sandbox Code Playgroud)

以下是导致错误的代码行:

var mapAction = new MapAction(MapActionType.POLYGONDRAGGED, []);
Run Code Online (Sandbox Code Playgroud)

这是原始的typescript -file 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

这是转换后的.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
Run Code Online (Sandbox Code Playgroud)

euv*_*uvl 56

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

export default class MapAction implements IMapAction {...
Run Code Online (Sandbox Code Playgroud)

并导入为:

import MapAction from './map_action_file';
Run Code Online (Sandbox Code Playgroud)

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

export class MapAction ...
export class MapSomethng ...
Run Code Online (Sandbox Code Playgroud)

并导入如下:

import { MapAction, MapSomething } from './map_action_file';
Run Code Online (Sandbox Code Playgroud)

  • 或者,从'./ map_action_file'`导入`import {MapAction}而不导出默认值 (4认同)
  • 缺少{}使我如此:`从'./Frak'导入{Frak};`修复了它。谢谢。 (2认同)

Žel*_*vić 10

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

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


Dat*_*sos 5

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

import LatLngLiteral from '';
Run Code Online (Sandbox Code Playgroud)

import { LatLngLiteral } from '';
Run Code Online (Sandbox Code Playgroud)