Tip 48: Leverage Community Knowledge with npm

In this tip, you’ll learn how to import external code with npm.

In the previous tip, you learned how to use code from different files. In this tip, you’ll learn how to use community code created by developers all over the world.

Access external code using npm

Not many years ago, if you wanted to use an open-source library, you were forced to either copy-paste code locally, download a library to your project, or include an external dependency using a <script> tag in your markup.

You’d get your code—unless an external source went down—but it was hard to keep dependencies up to date, particularly if you were storing them locally. Not only was it hard to maintain, but you also had to write your custom code assuming the library would be there. This made code really hard to read and test because you never explicitly included anything.

Those days are gone. You can now download code directly to your project, control versions, and import code into individual files using familiar conventions.

You manage all this with a tool called the node package manager, or npm. There are a few alternatives, such as Facebook’s yarn project, but they work in mostly the same way, so don’t worry too much about the differences.

npm is an important project, and you’ll mostly use it for importing code, but it can do a lot more. With npm, you can set your project’s metadata and configuration information, run command-line scripts, and even publish your project for others to use.

Set up

The setup instructions given below have already been done for you on the platform.

To run the code locally, you’ll need to have Node.js installed. After that, you’re ready to go. When you install Node.js, you also install npm.

After Node.js and npm are installed, you need to initialize a project. Open up a terminal, go to the root of your project, and type npm init. This will start up a configuration tool that will create a package.json file for you.

This package.json file will contain metadata information for your project, such as name, description, license, and so on. It will eventually contain all the external code dependencies. It’s important to note that npm init only creates the package.json file. It doesn’t set any other hidden files or directories. You don’t need to worry about cluttering your file system.

If you aren’t sure what you want, don’t worry. You can change all of that information later. Go with the defaults at first if you have any doubts. When you finish, you’ll have a file that looks like this:

Get hands-on with 1000+ tech skills courses.