Npm is an excellent package manager for JavaScript and for sure it’s the first choice when it comes to managing packages and dependencies, but sometimes we just need to install a library from GitHub.
Note: npm is both the name of the Package Manager and the name of the command line client. In this tutorial we will do without the Package Manager but will use the npm cli. You can replace it with any other task runner.
When not to use npm?
- When you have a free plan, and you need a private package (pro plan costs 7$ per month)
- When you have a small project with just one or two dependencies
- When your custom library is already sitting on GitHub, Bitbucket or Gitlab
- When you don’t know how to work with npm locally (Yes, it’s possible and here I explained how to do it, but it’s definitely more complicated)
Quick way to install from any source
Of course, you can download the package and just place it in your codebase. But I advise you against doing so, you would lose the ability to easily update it, and then you would have to maintain it. Do this instead:
- Create an
install.js
file with the following:
// Edit these three constants
const repo = 'git@github.com:nuovecode/my-module.git';
const path = 'src/app/foo'
const version = '1.0.0'
//Don't change anything
const util = require('util');
const exec = util.promisify(require('child_process').exec);
module.exports = (async () => {
try {
console.log(`Download ${repo} ...`)
await exec(`if [ -d ${path} ]; then rm -Rf ${path}; fi`);
await exec(`mkdir ${path}`);
await exec(`git clone -b ${version} ${repo} ${path}`);
console.log(`${repo} added successfully!`)
} catch (error) {
console.error(error);
}
})();
Only the first three constants should be edited:
- repo SSH url of the repository you want to install
- path The path inside your project where you want to install your module
- version The version of the module you want to install. Can be a tag or a branch
(if you want the latest one use
main
ormaster
but be careful about updates)
- Now Include the script you just created in your
package.json
as a preinstall script:
{
"name": "name-of-your-app",
"version": "1.0.0",
"scripts": {
"start": "...",
"build": "...",
"watch": "...",
"test": "...",
"preinstall": "node path/install.js"
}
}
- Ignore the folder where your module has been downloaded:
in the
.gitignore
, add the linesrc/app/foo
(the path you used in the path constant of theinstall.js
script) - And that is. Now each time you run
npm install
you will download the module into your project, and you can continue working on it as it will be under version control.
Easy, isn’t it? Sometimes in life the simplest way is the best
Gran Torino, Clint Eastwood 2008