2020-03-06
|~2 min read
|349 words
In node projects, many times a package will have its own CLI. React, Storybook, Typescript and Gatsby all have their own for example.
How do we actually use those CLIs within a project? This is one of those topics that I don’t normally think about because it’s usually handled by the base case.
Well, there are a few different ways:
Below, I’ll walk through all of these using Gatsby as an example.
The most common solution I’ve found, particularly for commands used frequently within a project is to add a script in the package.json
.
For example, my Gatsby starter came with a dev
and build
script included:
{
"scripts": {
"build": "gatsby build",
"dev": "gatsby develop"
}
}
But what if you want to build and then serve the site? You can add another line to the scripts:
{
"scripts": {
"build": "gatsby build",
"dev": "gatsby develop",
"serve": "gatsby serve"
}
}
This works well, but it can also lead to a ballooning of scripts which might become unweildly over time.
Another approach is to install the package globally and then use that to run your more ad hoc scripts.
For example:
$ npm install --global gatsby
$ pwd
Users/stephen/my-gatsby-project
$ gatsby serve
I’ve been having issues with globally installed packages lately, however, so I tend to avoid them.
Fortunately, it’s possible to run the command without installing a package globally by reaching into your node_modules
folder (just like the script is doing):
$ pwd
Users/stephen/my-gatsby-project
$ ./node_modules/.bin/gatsby serve
The other benefit here is that you never run itno the situation where your globally installed package is a different version from the local one!
In most cases, using a script is a great solution. When you want a quick ad hoc script and don’t want to install the package globally though, knowing how to reach into your node_modules
folder can be really useful!
Happy hacking!
Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!