代码之家  ›  专栏  ›  技术社区  ›  Juicy

从另一个模块导出模块类

  •  0
  • Juicy  · 技术社区  · 8 年前

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

    export default class NetMap {...}
    

    我还有一个模块 helloworld 我想出口(不是作为 default )整个 网络地图 类,以便另一个模块可以访问 网络地图 通过使用:

    import * as helloworld from 'helloworld'
    
    const x = helloworld.NetMap()
    

    这可能吗?会是什么 export 属于 网络地图 看起来像是在 地狱世界 模块?

    2 回复  |  直到 8 年前
        1
  •  1
  •   Danziger    8 年前

    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();
    

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

    网络地图.js

    export class NetMap {
        ...
    }
    

    地狱世界.js (通常称为 桶 )以下内容:

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

    然后,在另一个模块中:

    从“./helloworld.js”导入*作为helloworld;
    
    const x=new helloworld.netmap();
    

    或:

    import { NetMap } from './helloworld.js';
    
    const x = new NetMap();
    
        2
  •  0
  •   kyle    8 年前

    我想我知道你在做什么,而且这似乎是有可能的。但如果我误解了,一定要告诉我。

    所以你有你的网络地图文件…

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

    然后你有你的helloworld文件,它使用netmap或者其他一些东西…

    // helloworld.js
    const netMap = require('./netMap')
    // import netMap from 'netMap'
    
    const helloWorld = _ => console.log('hello world!')
    
    module.exports = { netMap, helloWorld }
    export { netMap, helloWorld }
    

    现在你有一个第三文件,你将导入所有的Hello World…

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