NPM Commands and Shortcuts You Should Know as a JavaScript Dev

Thomas Sentre - Feb 11 '23 - - Dev Community

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 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:

npm install ioredis
Enter fullscreen mode Exit fullscreen mode

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 , 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 . 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:

{ 
“version”: 4.28.2,
“dist-tags”: {
“latest”: 4.28.2
},
 }
Enter fullscreen mode Exit fullscreen mode

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:

$ npm install <package-name>@tag
$ npm install <package-name>@version
$ npm install <package-name>@version-range
Enter fullscreen mode Exit fullscreen mode

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:

$ npm uninstall <package-name>
Enter fullscreen mode Exit fullscreen mode

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:

$ npm update
Enter fullscreen mode Exit fullscreen mode

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:

$ npm update <package-name>@version
Enter fullscreen mode Exit fullscreen mode

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:

$ npm audit
Enter fullscreen mode Exit fullscreen mode

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:

$ npm audit fix
Enter fullscreen mode Exit fullscreen mode

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:

$ npm audit json
Enter fullscreen mode Exit fullscreen mode

Or, if you prefer plain text:

$ npm audit readable
Enter fullscreen mode Exit fullscreen mode

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

$ npm audit fix dry-run
Enter fullscreen mode Exit fullscreen mode

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:

$ npm dedupe
Enter fullscreen mode Exit fullscreen mode

or

$ npm ddp
Enter fullscreen mode Exit fullscreen mode

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:

$ npm prune
Enter fullscreen mode Exit fullscreen mode

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.

$ npm login
Enter fullscreen mode Exit fullscreen mode

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

$ npm publish
Enter fullscreen mode Exit fullscreen mode

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 @/ (or do npm init — scope=). 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:

npm unpublish [<@scope>/]<package-name>[@<version>]
Enter fullscreen mode Exit fullscreen mode

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:
npm deprecate <pkg>[@<version range>] <message>
Enter fullscreen mode Exit fullscreen mode

That will mark your package as deprecated, optionally applying a message you can specify about what happens.

  1. Add private: true to package.json to prevent accidental publishing of any private repository.

  2. To generate a package.json file quickly, use the command: npm init — y

  3. Don’t delete the package.json, but you can delete the package-lock.json before committing it.

  4. You need to run npm install after cloning a project from a Git repository.

  5. 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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .