【问题标题】:Export module class from another module从另一个模块导出模块类
【发布时间】:2018-06-26 00:03:17
【问题描述】:

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

export default class NetMap {...}

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

import * as helloworld from 'helloworld'

const x = helloworld.NetMap()

这可能吗? NetMapexporthelloworld 模块中会是什么样子?

【问题讨论】:

    标签: javascript import ecmascript-6 export


    【解决方案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();
    

    【讨论】:

      【解决方案2】:

      我想我可以说出你想要做什么,而且这看起来确实是可能的。但如果我误解了,请告诉我。

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

      // 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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-08
        • 1970-01-01
        • 2020-05-18
        • 1970-01-01
        • 2020-11-15
        • 1970-01-01
        相关资源
        最近更新 更多