Monday, March 26, 2018

Node.js module.exports

NodeJS specific feature is when you assign a reference to a new object to exports instead of just adding properties and methods to it like in the last example provided by Jed Watson in this thread. I would personally discourage this practice as this breaks the circular reference support of the CommonJS modules mechanism. It is then not supported by all implementations and Jed example should then be written this way (or a similar one) to provide a more universal module:
(Test.js):
exports.run = function() {
    console.log("Hello World!");
}
(app.js):
var sayHello = require('./Test');
sayHello.run(); // "Hello World!"
Or using ES6 features
(Test.js):
Object.assign(exports, {
    // Put all your public API here
    sayhello() {
        console.log("Hello World!");
    }
});
(app.js):
const { sayHello } = require('./Test');
sayHello(); // "Hello World!"

No comments :

Post a Comment