NPM Commands and Shortcuts You Should Know as a JavaScript Dev
Tags: webdev, javascript, beginners, npm
Published: 2023-02-11 00:48:25

Whether you are a newbie or a proficient in JavaScript world, you probably already use or will use those annoying three little letters — npm — in a command line, trying despairingly to download packages, which are reusable JavaScript modules from a central package registry. But do you know with this command that is possible to do some amazing actions that will help you to accelerate the development of your application?

In this post, I will provide you the most prominent NPM commands, shortcuts, and tips that will help you increase your productivity and efficiency as a JavaScript Developer.

In this post, we will cover the following topics:

- Definition of NPM.
- Using the npm package management system to manage application dependencies, to publish and unpublish packages.
- Installing a package by version number.
- Difference between package.json and package-lock.json file.
- Auditing package security using NPM command.
- and much more

Before getting started, let’s review what is NPM and how to use it.

### What is NPM?
Conceptually, NPM, which stands for Node Package Manager, is similar to tools such as PiP (Python), RubyGems (Ruby on Rails), apt-get (Debian), rpm/yum (Red Hat/Fedora), CPAN (Perl), or PEAR (PHP). Released in 2010, NPM is a package management and distribution system for Node.js, an environment for building server-side applications. Its purpose is to publish and distribute Node.js packages over the internet using a simple command-line interface. In recent years, it has also become widely used for distributing front-end libraries like React or TailwindCss that are not Node.js modules. With npm, you can quickly find packages at [npm website](https://www.npmjs.com/) to serve specific purposes, download them, install them, or manage packages you’ve already installed.

### How to use NPM
Using npm is simple, it is merely another command to run from a command prompt, just like Node is. For example, let’s say you create a directory called _tester_ and initialize your project using the command: `npm init –yes`. A file named _package.json_ is autogenerated inside this folder. This file contains all the information about your project. After that, you execute the following command:

```javascript
npm install ioredis
```
Here, _npm_ is the Command Line Interface (CLI) program that is NPM itself and install is one command you can issue to it. Then, _ioredis_ is an argument to that command, and this is the general form that most of your interactions with NPM will take.

By executing this last command, a new directory called _node_modules_ will be created inside the tester folder. This directory will contain a lot of …. well, a lot of things you typically don’t need to worry about too much! In short, though, it’s all the code that makes up the _ioredis_ module.

### Difference between package.json and package-lock.json
By using the last command: `npm install ioredis`, two file called _package-lock.json_ and _package.json_ are also automatically generated. Yes, you think the _package.json_ file is similar to _package-lock.json_ file. But there is a small difference between them. The _package.json_ contains all the info of your project, particularly the dependencies or modules and their local versions that are used in your project. The _package-lock.json_ is simply a replica, versioned dependency tree of the package.json file. It also includes the dependencies and devDependencies that you used.

### NPM global and local packages
Packages are either installed in local or global mode. Until now, we have installed packages in local mode.

Let’s know how to install packages in these two modes.

- **Local packages** are installed in the directory where you run _npm install <package-name>_, and they are put in the _node_modules_ folder under this directory.

- **Global packages** are all put in a single place in your system (exactly where depends on your setup), regardless of where you run _npm install -g <package-name>_. Generally, a package installed globally provides an executable command that you run from the shell (CLI), and it’s reused across projects. Global mode packages are available from the command-line interface (CLI), while packages in local mode are installed in node_modules folder of the parent working file. Great examples of popular global packages which you might know are _nodemon_, _grunt-cli_, _forever_, _cross-env …_

### Installing a package by version number
Version number matching in npm is powerful and flexible. With it, you can target a specific release of a given package or any version number range. By default, npm installs the latest version of the named package, as we did in the previous section. Whether you take the default or specify a version number, npm will determine what to install. The package version is declared in the package.json file, so let’s look at the relevant fields:

```json
{ …
“version”: “4.28.2”,
“dist-tags”: {
“latest”: “4.28.2”
},
… }
```

The version field obviously declares the current package version. The dist-tags field lists symbolic tags that the package maintainer can use to aid their users in selecting the correct version. This field is maintained by the _npm dist-tag_ command. The npm install command supports these variants:

```shell
$ npm install <package-name>@tag
$ npm install <package-name>@version
$ npm install <package-name>@version-range
```

The last two are what they sound like. You can specify _ioredis@4.28.0_ to target a precise version, or _ioredis@”>3.1.0 < 4.0"_ to target a range of ioredis V3 versions.

The version match specifiers include the following choices:

- _Exact version match_: 4.28.0
- _At least version N_: >4.28.0
- _Up to version N_: <4.28.0
- _Between two releases_: >=4.24.3 <4.28.3

The _@tag_ attribute is a symbolic name such as _@latest_, _@stable_, or _@canary_. The package owner assigns these symbolic names to specific version numbers and can reassign them as desired. The exception is @latest, which is updated whenever a new release of the package is published.

### Uninstall Package
If you want to uninstall a package already installed, use the command:

```javascript
$ npm uninstall <package-name>
```

### Updating package
Once you have a project set up, you may on occasion want to update the packages it depends on. This is very easy to do:

```javascript
$ npm update
```

Yep, that’s it! NPM will go off and update all packages to the latest version. If you want to update a package to a specific version, use this command:

```javascript
$ npm update <package-name>@version
```

### Auditing Package Security
The sad reality is that, sometimes, packages you use will be discovered to have security vulnerabilities, just like any software you use. But, being aware of this, the NPM team has constructed a useful command for dealing with this:

```javascript
$ npm audit
```

Running this command will scan your package.json file and submit the list of dependencies to the default NPM registry requesting a report on any known vulnerabilities in them. This report will also include information on how to remediate. But if you want the quick answer, run this command:

```javascript
$ npm audit fix
```
That will cause NPM to update any vulnerable packages with the newest available version that hasn’t had the vulnerability reported in it.

If you would like to see a detailed audit report, execute:

```javascript
$ npm audit –json
```

Or, if you prefer plain text:

```javascript
$ npm audit –readable
```
Finally, if you would like to see what npm audit fix would do without literally doing it, you can use:

```javascript
$ npm audit fix –dry-run
```

### Deduplication and Pruning
One of the complaints you will commonly see about NPM and Node is that the size of the _node_modules_ directory can ballon in a hurry. Fortunately, you rarely will need to dive into it, but it’s still a question of disk space, and while disk space is cheap these days, it’s still not chic to be wasteful!

NPM provides two commands for dealing with this situation, starting with:

```javascript
$ npm dedupe
```
or

```javascript
$ npm ddp
```

This command searches through the tree of packages in _node_modules_ and looks for opportunities where packages can be moved up the tree and shared between dependencies, thereby reducing redundancy and saving space. The package tree is built up as you install packages and as NPM installs the packages, it depends on, and so on.

Sometimes, packages will have dependencies in common, but being a tree, branches are mostly independent. This command attempts to reorganize those branches to make them more efficient.

The second command is this:

```javascript
$ npm prune
```

This command will examine the installed packages and look for any that may no longer be needed. This typically happens when you uninstall packages especially if you have done a dedupe at some point.

### Publishing and unpublishing package
Publishing to a registry is quite simple! First, you will need to, well, write your package! Gotta have something, to publish, right? You don’t need to do anything special, but npm init your project and cobble your code together.

After that, go to the registry website and create a new account. You will need to log in to that account from the command line.

```javascript
$ npm login
```

This will prompt you for your username, password, and email address. Once you’re logged in, publishing is a snap:

```javascript
$ npm publish
```

By using this command your package will be published with its default name. Well, hold up, there’s one thing that can go wrong: your package name could already be taken. It’s always a good idea to do an npm search for the name first, but assuming the name isn’t taken (or you’ve changed it after discovering a collision), then it’ll be published and available in the registry immediately.

#### Tip
If the name you want isn’t available, NPM also lets you publish to a scope. This means, for example, you can change the name to _@<username>/<package-name>_ (or do _npm init — scope=<username>_). You’ll then also need to add –access public to the publish command. That way, as long as your package name is unique within the scope, then you’re good to go; the name can be used in other scopes without issue (and no scope is effectively the default scope!). So, if, like domain names, the one you want is taken, there’s a way around it in NPM land. If you for some reason down the line decide you need to remove your package from the registry, it’s as simple as:

```shell
npm unpublish [<@scope>/]<package-name>[@<version>]
```
Now, we have explored the most pertinent NPM commands that will be useful for you. But there are also some useful npm commands that we did not touch. You can use the command_ npm help_ to get help or move to the npm documentation website to discover more commands.

Now that we have known NPM deeply, let us enumerate some tips, tricks, and shortcuts that will help you use NPM efficiently.

### Tips and Shortcuts

1. Removing a package is generally considered bad form because other developers may be depending on it. The better thing to do is to use another command:

```shell
npm deprecate <pkg>[@<version range>] <message>
```
That will mark your package as deprecated, optionally applying a message you can specify about what happens.

2. Add _private: true_ to _package.json_ to prevent accidental publishing of any private repository.

3. To generate a package.json file quickly, use the command: _npm init — y_

4. Don’t delete the _package.json_, but you can delete the _package-lock.json_ before committing it.

5. You need to run _npm install_ after cloning a project from a Git repository.

6. It is not recommended to push _node_modules_ to your source control repo such as Git. Add _node_modules_ to a .gitingore file before pushing your project, if you are using Git as version control.

### Conclusion
Now that you know the essential NPM commands and shortcuts, it's time to put them into action! Go ahead and try them out in your next project. And, if you come across any other helpful NPM commands, don't hesitate to share them in the comments below. Your contribution can help make the world of JavaScript development even more efficient and streamlined. So, let's get started and make the most out of NPM!


**THANK YOU FOR READING** 
I hope you found this little article helpful.  Please share it with your friends and colleagues. Sharing is caring.

Connect with me on [various platforms](https://bio.link/thomassentre)