DEV Community

Cover image for GitHub URLs in package.json
Michal Bryxí
Michal Bryxí

Posted on • Edited on

GitHub URLs in package.json

package.json file in your node project contain (among others) links to the packages that your projects needs to run.

To add new package dependency, you can run npm add command:

 npm add chalk
Enter fullscreen mode Exit fullscreen mode

And after that respective package will be added to the dependencies section of your package.json:

{
  "name": "sandbox",
  "main": "index.js",
  "dependencies": {
    "chalk": "^4.1.2"
  }
}
Enter fullscreen mode Exit fullscreen mode

But what if instead of a published npm package I want to use a branch that is living on GitHub? Luckily package.json definition allows GitHub URLs. The syntax is one of:

github:[user]/[project]
github:[user]/[project]#[commit-sha]
github:[user]/[project]#[branch]
github:[user]/[project]#[tag]
Enter fullscreen mode Exit fullscreen mode

The github: part is optional, but gives some context to your future self.

Where user and project you can extract from the GitHub URLs of respective repositories: https://github.com/[user]/[project]/

So for example to install commit 95d74cbe8d3df3674dec1445a4608d3288d8b73c of the package/project chalk (which happens to have GitHub user of the same name) I would have to specify:

{
  "name": "sandbox",
  "main": "index.js",
  "dependencies": {
    "chalk": "github:chalk/chalk#95d74cbe8d3df3674dec1445a4608d3288d8b73c"
  }
}
Enter fullscreen mode Exit fullscreen mode

Semver

There is one more curious format that can be used in GitHub URLs and that is semver. The syntax is:

github:[user]/[project]#semver:[semver]"
Enter fullscreen mode Exit fullscreen mode

So for example to install chalk with semver ^2.4.1 we should put following into our package.json:

{
  "name": "sandbox",
  "main": "index.js",
  "dependencies": {
    "chalk": "github:chalk/chalk#semver:^2.4.1"
  }
}
Enter fullscreen mode Exit fullscreen mode

Photo by JJ Ying on Unsplash

Top comments (2)

Collapse
 
lulalaby profile image
Lala Sabathil

You have a typo here 🤣
Image description

Collapse
 
michalbryxi profile image
Michal Bryxí

Ha! Actually took me a while to spot the githug. Thanks for pointing that out!