Use Github branch as dependency in package.json

Use Github branch as dependency in package.json

Image for postPhoto by Paul Rysz

Need to track a forked version of a node codebase, or separate out components of a project into their own repos?

Update: 2/15/18

Realized this can be accomplished in a single CLI command:

npm install –save username/repo#branch-name-or-commit-or-tag

The above installs a node package from github into your node_modules folder and automatically adds the dependency to your package.json!

This works, but it?s more of a workaround than a real solution.

Consider publishing your package to NPM (or the JavaScript package registry of your choice), it?s the proper option for package management. A git branch can be deleted or altered at any time, so there?s no guarantee of stability for the dependency. If that?s important for you, please do publish to a registry!

Installing from a git branch also breaks your ability to run npm update to update the dependency, forcing you to uninstall and reinstall the package in order to pull any new changes pushed to the branch.

If you are determined to do this, it?s marginally safer to install at a specific commit hash or git tag instead of a branch name. This way your dependency is tied to a specific commit, instead of whatever the latest commit is on a branch. However, the above caveats about disappearing dependencies and broken update paths still apply! You?ve been warned ?.

h/t to Tierney Cyren for pointing out the flaws in this method

To npm install a public project that is hosted on Github, and not the NPM registry, add the Github repo to package.json dependencies using the username/repo#branch-name format.

// package.json…”dependencies”: {“botkit”: “jonchurch/botkit#multi-hears”,}….

Run npm install and npm will download the project and save it into your /node_modules/ folder.

After new changes have been pushed to the branch, delete the package from your node_modules and run npm install again. Something like this:

npm uninstall botkit && npm install jonchurch/botkit#multi-hears

That?s it! Now you can track all the unpublished packages you want from github.

If you liked this, follow me on twitter for more Node.js content!

23