Exporting classes with node.js

后端 未结 4 920
清歌不尽
清歌不尽 2020-12-13 13:25

I have the following test code that is being ran by jasmine-node in a file called bob_test.spec.js

require(\'./bob\');

describe(\"Bob\", functi         


        
4条回答
  •  清歌不尽
    2020-12-13 13:45

    If you can use ECMAScript 2015 you can declare and export your classes and then 'import' your classes using destructuring with no need to use an object to get to the constructors.

    In the module you export like this

    class Person
    {
        constructor()
        {
            this.type = "Person";
        }
    }
    
    class Animal{
        constructor()
        {
            this.type = "Animal";
        }
    }
    
    module.exports = {
        Person,
        Animal
    };
    

    then where you use them

    const { Animal, Person } = require("classes");
    
    const animal = new Animal();
    const person = new Person();
    

提交回复
热议问题