Can you export multiple classes from a single Nodejs Module?

后端 未结 2 533
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-14 00:25

Currently, I have 4 Child Classes each in their own file. I\'m requiring them all in the same file. I am wondering if I can contain all 4 of those classes in a single module

相关标签:
2条回答
  • 2020-12-14 01:16

    You can also do this in a shorter form, using destructuring assignments (which are supported natively starting from Node.js v6.0.0):

    // people.js
    
    class Jack {
      // ...
    }
    
    class John {
      // ...
    }
    
    module.exports = { Jack, John }
    

    Importing:

    // index.js
    
    const { Jack, John } = require('./people.js');
    

    Or even like this if you want aliased require assignments:

    // index.js
    
    const {
      Jack: personJack, John: personJohn,
    } = require('./people.js');
    

    In the latter case personJack and personJohn will reference your classes.

    A word of warning:

    Destructuring could be dangerous in sense that it's prone to producing unexpected errors. It's relatively easy to forget curly brackets on export or to accidentally include them on require.


    Node.js 12 update:

    Lately ECMAScript Modules received an extended support in Node.js 12.*, introducing the convenient usage of import statement to accomplish the same task (currently Node should be started with a flag --experimental-modules in order to make them available).

    // people.mjs
    
    export class Jack {
      // ...
    }
    
    export class John {
      // ...
    }
    

    Notice that files that adhere to modules convention should have an .mjs extension.

    // index.mjs
    
    import {
      Jack as personJack, John as personJohn,
    } from './people.mjs';
    

    This is much better in a sense of robustness and stability, as an attempt to import non-existing export from the module will throw an exception similar to:

    SyntaxError: The requested module 'x' does not provide an export named 'y'

    0 讨论(0)
  • 2020-12-14 01:18

    You can export multiple classes like this:

    e.g. People.js

    class Jack{
       //Member variables, functions, etc
    }
    
    class John{
       //Member variables, functions, etc
    }
    
    module.exports = {
      Jack : Jack,
      John : John
    }
    

    And access these classes as you have correctly mentioned:

    var People = require('./People.js');
    var JackInstance = new People.Jack();
    var JohnInstance = new People.John();
    
    0 讨论(0)
提交回复
热议问题