문제

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.

도움이 되었습니까?

해결책

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)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 softwareengineering.stackexchange
scroll top