12

Is there any convention to where we should declare the module.exports no Javascript/Node.js module files?

Should it be in the beginning of the file like:

module.exports = Foo;

function Foo() {
    this.bar = 'bar';
}

Foo.prototype.getBar = function() {
    return this.bar;
}

Or should it be in the end of the file:

function Foo() {
    this.bar = 'bar';
}

Foo.prototype.getBar = function() {
    return this.bar;
}

module.exports = Foo;

I know that there is no technical difference. The first example is perfectly valid because of declaration hoisting.

So I was wondering if there are some kind of best practices.

3
  • One advantage of leaving it on the end is that you can use function objects (var Foo = function()...), and yet another way of declaring it is directly (module.exports.Foo = function()...).
    – Marcelo
    Jan 12, 2016 at 15:47
  • I could just var Foo = function Foo()... and it would work as well. Jan 12, 2016 at 16:30
  • Advantage of putting it at the top: you can see the API of your module at a glance (without having to scroll down). Dec 24, 2016 at 18:45

1 Answer 1

5

There are certainly lots and lots of options, which are all commonly used. But that's terribly annoying. I like to put it at the end, because that works under all circumstances. Whenever I find myself doing something fancy with module.exports, there is probably a better way to do it.

Most importantly, as always, be consistent. And be consistent in your team.

EDIT: On the same notion, I like to have all require statements at the beginning. My Node.js files always look like this:

"use strict";

const fs = require("fs");
const MyClass = require("./MyClass");


class MyOtherClass extends MyClass {}

module.exports = MyOtherClass;

Nothing fancy, just the way you would expect it. One class per file, one file per class. Files named after the class they contain, with consisten upper/lowercasing. Have a look at this node module, for some examples: yaioc (disclaimer: I'm the author, and this is shameless advertising)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.