JavaScript: How to use NPM to install packages

NPM or “npm” stands for Node Package Manager. It is the default package manager for the JavaScript runtime environment Node.js. The NPM program is installed on your computer when you install Node.js. The website contains hundreds of thousands of free open source code packages that can be downloaded and used via npm.

Downloading Individual Packages

Individual Node.js packages can be downloaded for use as modules in your projects by typing the npm install command in your command window. First you cd to the current project directory. For example:

cd C:\Users\christon\Desktop\Projects\travel-site

Then type npm install and the name of the module you want to use. For example, jquery:

npm install jquery

When npm installs a package, it creates a folder in your project called “node_modules” and inside this folder there is another folder with the name of the package that was installed. For example:

From the website:

npm init creates package.json

The package.json file tells Node.js which modules or packages are installed for your project. This doesn’t have to be created manually. The command npm init will generate this file automatically for you. First cd to the project folder, then run this command:

npm init

Then click enter a few more times and you should see this confirmation screen:

When this step is complete, there is a package.json file in the project folder.

Note: In the previous example I used the command npm install jquery --save. The –save option instructs npm to include the package inside of the dependencies section of your package.json file automatically (which saves the extra step of doing this manually). As of npm 5.0.0, installed modules are added to the package.json file as a dependency by default, so the –save option is no longer needed. This of course happens only if a package.json file already exists in your project folder.

Use package.json to install list of packages

Let’s say there are a couple of packages listed in your package.json file that were added by a combination of using npm init and npm install. There is another way to use the package.json file that is very handy. If you want to work on a new project and don’t have any of the modules installed yet, you can get a pre-defined package.json file and use that to install all of the modules you need. Just place the pre-defined package.json file into your project folder, (overwriting the previous version if necessary), and run npm install with no package specified. If no package is specified, npm will open the package.json and install all of the modules it finds listed there.

For more about using NPM, see: