NPM Tips and Tricks

12 useful NPM tips and tricks for more productive JavaScript coding.

Ankit Jain
Bits and Pieces

--

NPM, Node Package Manager, is the package manager for the JavaScript programming language. Any developer who is working with Javascript has used this wonderful CLI tool to install the dependencies for their project.

In this article, I will be sharing NPM tips and tricks that can boost your productivity and let you use NPM in a smarter and more efficient way.

1. Initialize your package

we can run npm init command to initialize our package but it will ask information about the package, author, etc. There is another way to automatically generate our package.json using the npm init -y command.

npm init -y

We can also set some the default init configuration like the author details etc. Let’s configure using npm config command.

npm config set init-author-name "Ankit Jain"
npm config set init-author-email "ankitjain28may77@gmail.com"

Let’s run npm init -y to automatically generate our package —

{
"name": "<name of the root dir>",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Ankit Jain <ankitjain28may77@gmail.com>",
"license": "ISC"
}

We can also extend the functionality of npm init by adding our own custom javascript file and configure it again using npm config

npm config set init-module <path-of-the-custom-file>

2. Install a package from other sources

NPM CLI also allows installing javascript packages from other sources like Bit, tarball file, GitHub repo, Bitbucket, and gist.

# Install a component from Bit (set Bit as a scoped registry)
npm config set @bit:registry https://node.bit.dev
npm i @bit/username.collection.component
# Install from tarball stored locally
npm i ./local-tarball-package.tgz
# Install tarball package from internet
npm i https://abc/xyz/package.tar.gz
# Install from github repo
npm i githubuser/reponame
# Install from bitbucket repo
npm i bitbucket:bitbucketuser/reponame
# Install from gist
npm i gist:gistID

Example: Install a Button component from Bit

Let’s say I’m looking for a Button component that one of my teammates has published to our component collection on Bit.

I’ll start by configuring Bit as a scoped registry:

npm config set @bit:registry https://node.bit.dev

Then, I'll head over to my team’s collection to find the button:

https://bit.dev/the_a-team/imperfect-components/button

I’ll go to the ‘Button’ component page and copy the command to install using NPM:

https://bit.dev/the_a-team/imperfect-components/button
npm i @bit/the_a-team.imperfect-components.button

My team’s name: “The A-Team”. Our collection name: “Imperfect Components”.

3. Clean install your package dependencies

we can run npm ci to clean install our package dependencies. It is generally used in automated environments like CI/CD platforms.

npm ci

It is different from npm install in the following ways —

  • It installs the exact version of the package that is mentioned in the package-lock.json file.
  • Removes the existing node_modules and runs a fresh installation.
  • It won’t write to package.json or lock file.
  • It doesn’t install individual packages similar to npm install.

4. Use shortcuts to install packages

This is the most useful feature that we can use to save our time while installing packages —

# Install package
npm install <package_name>
Shortcut: npm i <package_name>
# Install devDependencies
npm install --save-dev <package_name>
Shortcut: npm i -D <package_name>
# Install dependencies (This is default)
npm install --save-prod <package_name>
Shortcut: npm i -P <package_name>
# Install packages globally
npm install --global <package_name>
Shortcut: npm i -g <package_name>

Install multiple packages in one command —

npm i express cheerio axios

Install multiple packages having the same prefix —

npm i eslint-{plugin-import,plugin-react,loader} express

5. NPM scripts

NPM scripts are the most useful feature. It supports custom-scripts apart from the pre-defined pre/post hooks (generally called lifecycle scripts) like —

  • preinstall — which runs before any package is installed.

npm run env lists all the npm environment variables present in our package. It also contains the package properties prefixed with npm_package_.

npm run env

The output will be —

npm_config_save_dev=
npm_config_legacy_bundling=
npm_config_dry_run=
npm_config_viewer=man
.
.
npm_package_license=ISC # Package properties
npm_package_author_name=Ankit Jain
npm_package_name=npm-tips-and-tricks # Name of our package
.
.

We can also access the above env variables in our code by process.env.npm_package_name and similarly other variables.

Configure own variables in package.json

We can pass our own variables as npm environment variables with the npm_package_config_ prefix by defining them in package.json file under config object. Let’s define the variable myvariable in our package.json file.

"config": {
"myvariable": "Hello World"
},

Now, let’s check it in env variable —

npm run env | grep npm_package_config_

We can see something like this —

npm_package_config_myvariable=Hello World

Define our custom scripts

npm run command shows all the scripts that we have defined in our package.json file. Let’s add some custom-scripts to our package.json —

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js",
"echo-hello": "echo \"Hello\"",
"echo-helloworld": "echo \"Helloworld\"",
"echo-both": "npm run echo-hello && npm run echo-helloworld",
"echo-both-in-parallel": "npm run echo-hello & npm run echo-helloworld",
"echo-packagename": "echo $npm_package_name",
"echo-myvariable": "echo $npm_package_config_myvariable",
"echo-passargument": "npm run echo-packagename -- \"hello\"",
"echo-pipedata": "cat ./package.json | jq .name > package-name.txt"
},

Now, we can see all commands added above by running this command —

npm run

The output will be —

# npm-tips-and-tricks (name of our package)
Lifecycle scripts included in npm-tips-and-tricks:
test
echo "Error: no test specified" && exit 1
start
node index.js
available via `npm run-script`:
echo-hello
echo "Hello"
echo-helloworld
echo "Helloworld"
echo-both
npm run echo-hello && npm run echo-helloworld
echo-both-in-parallel
npm run echo-hello & npm run echo-helloworld
echo-packagename
echo $npm_package_name
echo-myvariable
echo $npm_package_config_myvariable
echo-passargument
npm run echo-packagename -- "hello"
echo-pipedata
cat ./package.json | jq .name > package-name.txt

Run a simple npm script —

npm run echo-hello# Output
> echo "Hello"
Hello

Run multiple scripts in a single npm script —

We can run multiple scripts using “&&”. Both the scripts run in series i.e one after the other.

npm run echo-both# Output
> npm run echo-hello && npm run echo-helloworld
> npm-tips-and-tricks@1.0.0 echo-hello
> echo "Hello"
Hello> npm-tips-and-tricks@1.0.0 echo-helloworld
> echo "Helloworld"
Helloworld

We can also run multiple scripts in parallel using “&”.

npm run echo-both-in-parallel# Output
> npm run echo-hello & npm run echo-helloworld
> npm-tips-and-tricks@1.0.0 echo-hello
> echo "Hello"
> npm-tips-and-tricks@1.0.0 echo-helloworld
> echo "Helloworld"
Hello
Helloworld

Use npm environment variable in npm script —

npm run echo-packagename# Output
> echo $npm_package_name
npm-tips-and-tricks-------------npm run echo-myvariable
# Output
> echo $npm_package_config_myvariable
Hello World

Pass arguments to another npm script —

We can use “” to pass arguments to npm script. In the below example, we pass “hello” as an argument to echo-packagename script.

npm run echo-passargument# Output
> npm run echo-packagename -- "hello"
> npm-tips-and-tricks@1.0.0 echo-packagename
> echo $npm_package_name "hello"
npm-tips-and-tricks hello

Use Pipe to pass data from one npm script to another —

npm run echo-pipedata# Output
> cat ./package.json | jq .name > package-name.txt
# Let's cat package-name.txt
cat package-name.txt
# Output
"npm-tips-and-tricks"

6. Quickly navigate to package docs

We can quickly navigate to docs of any npm package by simply running this command —

npm docs <package-name>
OR
npm home <package-name>

If we want to check for any open issues or file any bug to npm package, we can also navigate to the website by running this command —

npm bug <package-name>

Similarly, npm repo <package-name> opens the GitHub repo page in the browser.

7. Removes duplicate packages

We can remove the duplicate dependencies by running npm dedupe command. It simplifies the overall structure by removing the duplicate packages and effectively sharing the common dependency across the multiple dependent packages. It results in a flat and deduplicated tree.

npm dedupe or npm ddp

8. Scan your application for vulnerabilities

we can run npm audit command to scan our project for any vulnerabilities in any of the dependency. It beautifully generates an output in a table format (we can also get the output in JSON) and also display, with other packages are dependent on this package if it is a multi-level/multi dependency.

npm audit fix automatically installs the patched version (if available) of all the vulnerable packages.

npm audit fix

9. Check our environment

We can use npm doctor command to run multiple checks on our environment like, whether our npm CLI has sufficient permissions to install the javascript packages and it is able to connect to the npm registry. It also checks for node and npm versions, validates cache for any corrupt packages.

npm doctor
npm doctor

10. Test your packages locally

NPM provides npm link command so that we can work and test our package iteratively. NPM link creates a symlink to our testing packages in the global npm modules folder and we can install this package into our testing application by simply running npm link <package_name> which will create a symlink from globally installed package to our root node_modules directory. It’s very useful while testing our local packages or using our own local npm packages.

cd /test-package (package name is helloworld)
npm link # Global symlink created
cd /application
npm link helloworld # Create symlink in node_modules

11. Check outdated packages

We can use npm outdated command to check for all the outdated npm packages. It also shows the latest version which should be installed for any outdated package.

npm outdated --long or npm outdated -l
npm outdated -l

We can also check for the latest version for any npm package by simply running this command —

# Shows the package information
npm view <package-name> or npm v <package-name>
# Shows the latest version only
npm v <package-name> version
# Shows the list of all versions
npm v <package-name> versions

12. List all the installed packages

We can list all the npm packages installed in our project simply by running npm list command. It will create a tree-structure showing the installed package and its dependencies.

npm list or npm ls 
npm list

We can make use of --depth flag to limit the search depth

npm ls --depth=1
npm ls — depth=1

Conclusion

In this article, we have learned about some of the useful NPM tips and tricks that we can use to increase our productivity. There can be a lot more of such tricks/tips. I would love to hear about them too in the comment section. It can help other developers.

Feel free to comment and ask me anything. You can follow me on Twitter and Medium. Thanks for reading! 👍

Learn More

--

--