TKrugg
TKrugg

Reputation: 2405

Define small named packages in your node application without having to publish them to npm

I'm wondering if there is a way with node to make a directory a containing package, like __init__.py does it in python?

Upvotes: 0

Views: 20

Answers (1)

Peter Lyons
Peter Lyons

Reputation: 145994

If your package is in a directory named "node_modules", and that directory is locatable somewhere shallower in the filesystem tree that the requiring module, require will find it. So you could do:

myapp.js
node_modules/mylib/package.json
node_modules/mylib/index.js

and myapp.js could just require("mylib"). This also works if that node_modules directory is anywhere shallower in the fs.

That's the simple solution but it isn't commonly done because most people want to .gitignore their node_modules directory and only put transient third party stuff in there.

This problem is extensively and exhaustively discussed in the gist better local require paths. I recommend reading through that for other approaches. Ultimately I think things end up as totally separate projects packaged as separate modules, so move toward that end state as soon as it is justified.

Upvotes: 2

Related Questions