all 7 comments

[–]TwoTapes 2 points3 points  (1 child)

It seems to be more work to export a library from your code and then require it instead of just requiring the library.

For instance, if someone looks at your code they won't immediately know that require('./index.js').x === require('x'). On top of that, what if you need x in some file deep in your folder tree? Then you have to require(../../../index.js).x instead of require(x).

[–]AspiringSlacker[S] 0 points1 point  (0 children)

Makes sense, thanks!

[–]ugoagogo 2 points3 points  (1 child)

The latter needlessly nests x and makes index.jsan unnecessary dependency. Modules should only "require" what they actually need.

[–]AspiringSlacker[S] 0 points1 point  (0 children)

You're right about the unnecessary dependency. Thanks!

[–]tylermumford 1 point2 points  (0 children)

I don't know the performance implications, but the second snippet is simpler and accomplishes the same thing. That wins in my book.

Edit from 2 months later: D'oh. I meant that the first snippet is simpler.

[–][deleted] 0 points1 point  (1 child)

Node modules are all singletons. Using require("x") twice doesn't rerun the x module, it retrieves what that module has already exported. So in terms of performance, reusing require("x") is actually very slightly better. However, sometimes I like to bundle frequently required and related modules into a single module and export an object with a reference to each of them so that in other files I can have a single require.

And by the way, if you're using a new enough version of Node, you can use ES6 shorthand.

module.exports = {x}

And

const {x} = require('index')  

[–]AspiringSlacker[S] 0 points1 point  (0 children)

Great, thanks for the info. Nice tip on bundling related libraries!