NPM Tips and Tricks

Little NPM secrets I learnt along the way

Install and test

You can install NPM dependencies and run tests with a single command:

1
2
3
4
$ npm it
# is equivalent to
$ npm install
$ npm test

If you use the package-lock.json file:

1
2
3
4
$ npm cit
# is equivalent to
$ npm ci
$ npm test

Run the command in a different folder

You can use the option --prefix <path/to/folder> to run NPM command in a particular folder. It works like a cross-platform cd <path/to/folder>; npm ... combination.

Let's say we are in a larger project, and the server we want to launch is in its own subfolder

1
2
3
4
5
6
app/
package.json # top-level project (optional)
sub/
folder/
package.json
index.js

Let's say the sub/folder/package.json has a "start" script

sub/folder/package.json
1
2
3
4
5
{
"scripts": {
"start": "node ."
}
}

Then we can install the dependencies and launch the app in the sub/folder all from the root app/ folder:

1
2
3
4
5
app/ $ npm --prefix sub/folder install
app/ $ npm --prefix sub/folder start
...
# after each command, the current directory is still app/
app/ $

Keep NPM dependencies up-to-date

  • using an external service like my favorite Renovate is my preferred way of keeping NPM dependencies up-to-date, read my Renovate blog posts
  • using local tool next-update gives you stats and runs the tests when upgrading each module to ensure the update does not break the project

Control the NPM cache

By default NPM downloads the modules to install into ~/.npm folder (and a similar user folder on Windows). You can change the cache folder using an environment variable npm_config_cache. You can also change it at run-time by providing --cache <path/to/folder> argument:

1
2
3
# install NPM dependencies using a local folder ".npm" to
# cache, prefer already found modules from the cache
$ npm i --cache .npm --prefer-offline

Generate random string

1
2
$ node -p 'crypto.randomBytes(4).toString("hex")'
657bfb6c

Pseudo-random using `Math.random()

1
Math.random().toString().slice(2, 10)

Extra tools

Here are some useful tools I use every day:

  • npm-quick-run lets you run NPM scripts without typing the full script name.
  • available-versions fetches the new versions for the given NPM package name and shows them in a nice console table.
  • as-a runs a given command, including NPM scripts with additional settings from the secrets file injected as environment variables.
  • bin-up Finds an installed tool in node_modules/.bin folders from current up to the git root.
  • bahmutov/npm-install is my GitHub action for simple NPM installs (with caching) when using GitHub Actions.

My NPM blog posts

Related posts