Exporting classes with node.js

后端 未结 4 913
清歌不尽
清歌不尽 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:31

    Improving marvin's answer:

    "use strict";
    var Bob = function() {}
    
    Bob.prototype.hey = function (text) {
      return "Whatever";
    }
    
    module.exports = new Bob();
    
    // another file
    var Bob = require('./bob');
    Bob.hey('text');
    

    So you can create an object passing it to module.exports module.exports = new Bob();

    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-12-13 13:56

    require returns an object, you should store it somewhere

    var Bob = require('./bob');
    

    and then use this object

    var bobInstance = new Bob();
    
    0 讨论(0)
  • 2020-12-13 13:56

    This should fix the error you were having while running your tests via jasmine-node:

    // Generated by CoffeeScript 1.6.2
    (function() {
      var Bob;
    
      Bob = (function() {
        function Bob() {}
    
        Bob.prototype.hey = function(what) {
          return 'Whatever.';
        };
    
        return Bob;
    
      })();
    
      module.exports = Bob;
    
    }).call(this);
    
    0 讨论(0)
提交回复
热议问题