NPM install git repos like a pro!

Hey guys! it been long, nevertheless I’m here and lets get started.

As a Javascript / Node.js developer, we use lot of npm packages and there’s standard command npm i package-name to install any package, but, do you know that you can install npm package directly from a git repo, even install from a specific branch, commit or tag.

To install any npm package from from github direclty we would use this command, in this instance we will use axios as example package.

npm i git+https://github.com/axios/axios.git

or if we want to install from a specific branch ( dev in this case ), we can use this command.

npm i git+https://github.com/axios/axios.git#dev

Similarly, if we want to install from a commit or a tag, we can use below example.

# using commit SHA at the end
npm i git+https://github.com/axios/axios.git#1025d1231a7747503188459dd5a6d1effdcea928
# using a tag
npm i git+https://github.com/axios/axios.git#v0.26.1

Installing private packages

this has helped me a lot in development when I need to use a custom private project as npm package in another project, it’s very handy, the same old thing with a user:password

# export your gitlab/github token. You can create this in your account settings
export $GITLAB_TOKEN='yourPrivateTokenString'
npm i git+https://user:$GITLAB_TOKEN@gitlab.com/customPackage.git

Amazing, isn’t it? now the challenges, this can cause issues with automatic deployments in case you are using CI/CD. So, if you need to configure this for an automatic deployment you can use postinstall script in package.json like the example below, make sure you have GITLAB_TOKEN shell variable declared before CI/CD script executes, this is provided by the CI tools itself, all you need is to configure it.

"postinstall": "npm install git+https://user:$GITLAB_TOKEN@gitlab.com/customPackage.git#xyz-branch"

that’s it folks, I hope you learned something useful.


Comments

Leave a Reply

%d bloggers like this: