Getting Started with npm in Visual Studio

npm and Visual Studio Header
Derived from photo by Markus Spiske / raumrot.com, CC-BY

The defacto package manager for JavaScript frameworks and tooling has become npm (node package manager). If you are a Visual Studio developer using Nuget through the years, this may be news to you. Likely, though, you understand there is a much bigger web development world outside of ASP.NET and Visual Studio – and this world uses npm. So why shouldn't you?

Go ahead, continue to get your .NET libraries from Nuget, but get your web frameworks from npm. This post teaches you the npm basics from a Visual Studio perspective. And while the command line is still currently the best place to use npm, there are some nice tricks to learn in Visual Studio as well.

This post assumes you are using Visual Studio 2015. Furthermore, web developers should install Mads Kristensen's prolific Web Extension Pack to get the most current web tooling for Visual Studio. If you don't see some of the described features below in your own installation, it's most likely because you don't have these tools installed.

Good Old Command Line

As much as Visual Studio developers love having a UI for their tools, npm is still most easily used at the command line. There are GUI tools such as Web Essentials Package Installer, but you may find these tools too simple to install packages the way you want.

Beyond installing packages, there are other advantages to using the command line. First, any new npm features debut in the CLI (command line interface) version of the tool so you can more easily take advantage of productivity enhancements. Second, your CLI skills are portable to other web development platforms, IDEs (integreated development environments), or text editors.

One extension in particular, Open Command Line, is a must for any command line work in Visual Studio. It is included in Web Extension Pack or as an individual download here. You can also get these extensions directly from within Visual Studio in the Extensions and Updates Manager. Open Command Line enables you to open the command line (Windows Command Prompt or PowerShell) from anywhere in Visual Studio with keyboard shortcuts or from a right-click in Solution Explorer.

Open Command Line Extension

Even better, when you use these shortcuts, the command line initializes to the directory from which you called the extension. So if you are writing code in C:\git\billion-dollar-idea\FlamingTomatoes\Web\index.html and decide you need a new npm package, press AltSpace and you get this:

Command Prompt

Sweet!!

The npm Command Line Basics

So you know how to get to the command line quickly from Visual Studio, now what? First, install NodeJS on your machine. Being that you are using this for development purposes, go head and install the current version instead of the LTS version.

Once installed, npm is available at the command line. Navigate to the directory of your project either manually or with the Open Command Line tool. This is the most basic installation of the Angular 1.x library:

npm install angular

This command makes a request to the public npm registry and downloads the latest version of the Angular package and installs it at the current directory in a folder called node_modules. Furthermore, npm also downloads any dependencies for Angular. You can read more about how npm structures the dependencies here.

The previous example installed the package to a local node_modules folder within the current directory. Some packages, such as those operating as command line tools, require global installation. These packages are not stored in a local node_modules folder but in a centralized location (e.g. C:\Users\<you>\AppData\Roaming\npm). Install packages globally using the -g parameter:

npm install typescript -g

What if you want a specific version of a package? When you want a specific version, append the version to the end of the package name. This installs Angular version 1.4.14:

npm install angular@1.4.14

The npm documentation has a great topic listing the various ways to specify package versions during installation.

Create a package.json File

Ideally, you want to keep a record of which packages you have installed in your project. This record is kept in a file called package.json. This file stores metadata for your application including a listing of packages that can be restored at a later time.

One import reason to keep this listing is source control. It's not ideal to store the contents of every package in source control. By storing the package.json file in source control, you don't have to keep the packages themselves in source control and each individual developer can restore these packages from the npm registry. If you are familiar with how Nuget uses packages.config, the concept is similar.

Visual Studio provides a template for creating a new package.json file making this process familiar to Visual Studio users. Right-click on your web project and select Add -> New File to display the Add New Item dialog. Then under the Web section, select the option for npm Configuration File.

Add New package.json

The contents of the file is incredibly minimal to the point where you may see the npm CLI show warnings. For your purposes of simply obtaining and recording npm packages, this package.json confriguration is sufficient and these warnings are unimportant.

{
    "version": "1.0.0",
    "name": "asp.net",
    "private": true,
    "devDependencies": {
    }
}

Of course, you can create the package.json file from the command line as well. Use the command:

npm init -f

Using the -f parameter creates the package.json file with default values that you can later edit. Otherwise, the init command prompts for a value for each field. The resulting file looks like this:

{
    "name": "folder",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies": {
    }
}

For the purposes of obtaining and using npm packages, the section you are most concerned about in package.json is "dependencies". When time to publish your project, make sure to learn more about the information listed in the package.json file.

Note: If you know that you do not want your project published online, consider setting "private": true. This setting helps to protect your project from accidentally being published because the npm registry refuses to publish projects with this flag enabled.

Install Packages to package.json

The npm tool allows you to save the packages you install to the package.json file by using parameters at the command line. For instance, to save Angular to your package.json file, use:

npm install angular -S

Using the parameter -S, npm saves the package in your existing package.json file and serializes the package listing in the "dependencies" configuration property.

{
    "dependencies": {
        "angular": "^1.5.8"
    }
}

Note: The caret ^ before the version number indicates that when npm attempts to re-install this package, it downloads this version or a later version compatible with this version. Read more about semantic versioning with npm.

Not all packages in npm are used for the same purpose. Some of the packages are frameworks used in the appliation, like Angular. Some of the packages are used during development like compilers and linters. These frameworks constitute developer tooling rather than application frameworks. npm makes this distinction in the package.json file by listing development dependencies in the "devDependencies" section.

{
    "devDependencies": {
        "typescript": "^2.0.3"
    }
}

Most of your needs are met using "dependencies" and "devDependencies". However, npm also has "peerDependencies" and "optionalDependencies" to register packages with your application. Find out more in the package.json documentation.

Also in Visual Studio, you have the option to type these packages directly in your package.json file with full IntelliSense support:

npm package.json IntelliSense support in Visual Studio

Restore Packages from package.json

As long as you have all of the packages listed in your package.json file, you can safely delete and restore your node_modules folder at any time. In fact, you probably should after installing a new dependency. Because npm resolves dependencies based on the order in which packages are installed, the only way to ensure that dependencies are installed in a consistent manner across machines is to install them from the same package.json file.

To install/restore packages, use the install command by itself at the directory containing an existing package.json file.

npm install

Alternatively, Visual Studio has a handy shortcut in Solution Explorer. Right-click on a package.json file and select the option to Restore Packages:

Visual Studio package.json Restore Packages

Looking Forward

In this tooling tour, you have seen how to install npm packages in various ways using the command line and using Visual Studio. This is still early days. Expect to see more tooling options from Visual Studio in the future.

Do you use npm packages in Visual Studio? What are your favorite tricks for working with them? Please leave a comment and let everyone know.

5 thoughts on “Getting Started with npm in Visual Studio”

  1. Hi, nice article. I wanted to quickly share it on social networks, but there isn’t a share button on your post. It would be great if you can add it.

  2. Hi, It was helpful but it would be great if you can extend it with a simple controller and view and have a simple running application

Comments are closed.