Skip to content

Instantly share code, notes, and snippets.

@mlrawlings
Last active June 14, 2022 11:15
Show Gist options
  • Save mlrawlings/cac0123a69165dad8f9f8a0fc91ee6b9 to your computer and use it in GitHub Desktop.
Save mlrawlings/cac0123a69165dad8f9f8a0fc91ee6b9 to your computer and use it in GitHub Desktop.
Using `src/node_modules/` for module development

Using src/node_modules/ for module development

The issue πŸ‘Ž

Often you'll find that you need utility methods or other functionality that might make sense as an external module that you could :tada: open source πŸŽ‰, but the process can be painful:

  1. create a directory outside the project
  2. initialize a git repo
  3. create a repo on github
  4. set the repo's remote origin to the github repo
  5. write the code
  6. publish the module
  7. install the module in your application
  8. realize you need another feature/bug fix
  9. make change
  10. publish the module
  11. re-install the module in your application
  12. goto #8

It's actually a little bit better with npm link, but still. So instead, you say "screw it", create a util/ directory, start putting scripts in there, and just require('../../../../util/my-foo').

The solution πŸ‘

We'll set up a node_modules/ directory under src/ so that you can require anything under this directory as if it were a module that had been installed from npm. So by putting it in src/node_modules/, you can require('my-foo') instead of ../../../../util/my-foo.

This src/node_modules/ directory would be separate from your top-level node_modules/ all your npm modules get installed. And unlike the top-level node_modules/, you would check this directory into source control.

The src/node_modules/ directory lives under your application so any changes you make here are immediately reflected in your application and you don't have the overhead of a separate project + repo.

You can now develop modules side-by-side with your application and they can evolve along with it until they are mature enough to stand on their own. You can then split the module out into it's own repository, πŸŽ‰ open source it πŸŽ‰, and publish it to npm.

Then you npm install --save my-foo and you're done. All your code was already using require('my-foo'), so nothing else needs to change.

That's it πŸ˜„

Go forth and write modular code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment