从另一个模块导出模块类

时间:2018-06-26 00:03:18

标签: javascript import ecmascript-6 export

我有一个模块netmap,该模块导出默认类NetMap

export default class NetMap {...}

我有另一个模块helloworld,我想导出(而不是作为default)整个NetMap类,以便另一个模块可以使用以下方式访问NetMap:< / p>

import * as helloworld from 'helloworld'

const x = helloworld.NetMap()

这可能吗? export中的NetMap中的helloworld是什么样的?

2 个答案:

答案 0 :(得分:1)

netmap.js

export default class NetMap {
    ...
}

helloworld.js(通常称为barrel):

import NetMap from './netmap.js';
import Foo from '...';
import ...

export {
    NetMap,
    Foo,
    ...
};

然后,在另一个模块中:

import * as helloworld from './helloworld.js';

const x = new helloworld.NetMap();

但是我个人更喜欢使用命名的导入/导出,所以我会这样做:

netmap.js

export class NetMap {
    ...
}

helloworld.js(通常称为barrel):

export { NetMap } from './netmap.js';
export { Foo } from '...';
export { ...

然后,在另一个模块中:

import * as helloworld from './helloworld.js';

const x = new helloworld.NetMap();

或者:

import { NetMap } from './helloworld.js';

const x = new NetMap();

答案 1 :(得分:0)

我想我可以告诉您您要做什么,这似乎是可能的。但是请让我知道我是否误会了。

所以您有您的netMap文件...

// netMap.js
class NetMap {
    constructor(a,b) {
        this.a = a
        this.b = b
    }
}

export default NetMap

然后您有了使用netmap以及其他一些东西的helloworld文件。...

// helloworld.js
const netMap = require('./netMap')
// import netMap from 'netMap'

const helloWorld = _ => console.log('hello world!')

module.exports = { netMap, helloWorld }
export { netMap, helloWorld }

现在您有第三个文件,将要导入所有的世界...

// otherModule.js
var helloWorld = require('./helloworld')
// import * as helloWorld from 'helloworld'
const x = new helloWorld.netMap(2,3)

console.log(x.a, x.b)
相关问题