TypeError:UnionFind不是构造函数

时间:2018-07-09 20:33:20

标签: javascript ecmascript-6

我具有以下用户定义的数据类型。

class UnionFind{

    constructor(n){
        this.items = n;
    }
    union(p, q){}

    connected(p, q){}

    find(p){}

    count(){}

}

我在以下代码中使用它。

import UnionFind  from "./unionFind.js";
const uf = new UnionFind(10)

我正在使用

node --experimental-modules union-find/client.mjs

出现以下错误,

TypeError: UnionFind is not a constructor
    at file:///Users/mstewart/Dropbox/data-structures-algorithms-princeton/union-find/client.mjs:13:12
    at ModuleJob.run (internal/modules/esm/ModuleJob.js:106:14)
    at <anonymous>

如果我将导出默认的UnionFind添加到数据类型,则会出现以下错误, 导出默认的UnionFind ^^^^^^

SyntaxError: Unexpected token export
    at new Script (vm.js:51:7)
    at createScript (vm.js:136:10)
    at Object.runInThisContext (vm.js:197:10)
    at Module._compile (internal/modules/cjs/loader.js:618:28)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
    at Module.load (internal/modules/cjs/loader.js:566:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
    at Function.Module._load (internal/modules/cjs/loader.js:498:3)
    at createDynamicModule (internal/modules/esm/Translators.js:53:15)
    at setExecutor (internal/modules/esm/CreateDynamicModule.js:50:23)

1 个答案:

答案 0 :(得分:2)

为了使Node模块使用importexport关键字,它应该具有.mjs扩展名。抛出UnionFind is not a constructor是因为未从模块中导出UnionFind

它应该是unionFind.mjs

export default class UnionFind {...}

unionFind.js

module.exports = class UnionFind {...}

导入为:

import UnionFind from "./unionFind";

请注意,与CommonJS的互操作将module.export视为ES模块中的默认导入。