Learn (and Practice) NPM
In our last article, we learned what the NPM package registry and manager are, and why they’re so helpful. Now, it’s time to get our hands dirty, and learn how to use the by jumping in and trying out a few basic commands.
After following this guide, you’ll know how to:
- Initialize a brand new project from scratch using
npm init - Run your code using NPM scripts
- Install packages from the NPM registry using
npm install
This article will show how you can use NPM to:
- Create your own project from scratch, leveraging functionality from existing libraries
- Work on an existing project or create one with a starter script, installing the packages that code needs on your own machine
Let’s create an extremely simple NPM project! You’ll start most (if not all) projects this way. At the end, you’ll have created a program that can generate a random rainbow ASCII cat! V(=^・ω・^=)v
-
Create a folder for your project.
Terminal window mkdir npm-shenaniganscd npm-shenanigansCreate a folder on your computer for your project. Navigate into it with
cd. -
Run
npm initto initialize your project.After running this command, you will be prompted to fill-in some details about your project. NPM will set the text between parentheses
()as your default values if a field is left empty.Terminal window npm initThis utility will walk you through creating a package.json file.It only covers the most common items, and tries to guess sensible defaults.See `npm help init` for definitive documentation on these fieldsand exactly what they do.Use `npm install <pkg>` afterwards to install a package andsave it as a dependency in the package.json file.Press ^C at any time to quit.package name: (npm-shenanigans) █Press enter as new prompts show up or type your own answers until you reach a final confirmation for the
package.jsonfile we’re about to create. Don’t worry too much about your answers at this stage, you can always edit them later! -
Confirm the creation of your
package.jsonfile.Terminal window npm initThis utility will walk you through creating a package.json file.It only covers the most common items, and tries to guess sensible defaults.See `npm help init` for definitive documentation on these fieldsand exactly what they do.Use `npm install <pkg>` afterwards to install a package andsave it as a dependency in the package.json file.Press ^C at any time to quit.package name: (npm-shenanigans)version: (1.0.0)description: A project to practice our NPM skills!entry point: (index.js)test command:git repository:keywords:author: boba-tanlicense: (ISC)About to write to /Users/boba-tan/npm-shenanigans/package.json:{"name": "npm-shenanigans","version": "1.0.0","description": "A project to practice our NPM skills!","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"author": "boba-tan","license": "ISC"}Is this OK? (yes) █Type
yesor press enter to confirm! Now that we’re done with ournpm initcommand, a new file calledpackage.jsonhas been created.This command might also create a
package-lock.json(which in practice you will never need to look at), and thenode_modules/folder, which stores the downloaded and installed code for this project. Even if these two things aren’t created already, installing a library later will still automatically add these files and folders, so don’t worry if you’re only seeingpackage.jsonfor now.Directory/
DirectoryUsers/
Directoryboba-tan/
Directorynpm-shenanigans/
- package.json
-
Run
npm pkg set type=moduleThis will turn on modern JavaScript features that NPM doesn’t set up by default. Since many modern libraries rely on these newer features, you might run into errors if you forget this step.
If you don’t set the type now, NPM will error when it run and tell you to set
"type": "module"in thepackage.json.Now, take a look, a new line has been automatically added to your
packacge.json.package.json {"name": "npm-shenanigans","version": "1.0.0","description": "A project to practice our NPM skills!","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1"},"author": "boba-tan","license": "ISC","type": "module"} -
(Optional) Ignore the
node_modules/folder when using git.If you use, or plan to use, git in your project, add a line for
node_modules/to your.gitignorefile to keep your repository clean.The
node_modules/folder is filled up using the information in thepackage.jsonandpackage-lock.jsonfiles, so you shouldn’t keep track of it in git.
-
Create a new file called
index.jsinside your project folder.Directory/
DirectoryUsers/
Directoryboba-tan/
Directorynpm-shenanigans/
- package.json
- index.js
Once you’ve created the file, open it in your text editor and add the following code to your file:
index.js console.log(":3c ~nyaa");Save the changes in your
index.jsfile. -
Run your code with node.
In the command line, run
node index.js.Terminal window node index.js:3c ~nyaa -
Run your code with an npm script.
Open you project’s
package.jsonfile in your text editor. Let’s take the command we used in the previous step and turn it into a script instead.In your
package.json, look for the line that says"scripts":{}. If you’ve been following closely, there’s probably a “test” script in there already with some messy code - feel free to ignore it. Let’s add a new script called “start” inside the curly brackets with our command from the previous step. Don’t forget to add commas between scripts!Your file should now look something like this:
package.json {"name": "npm-shenanigans","version": "1.0.0","description": "A project to practice our NPM skills!","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1""test": "echo \"Error: no test specified\" && exit 1","start": "node index.js"},"author": "boba-tan","license": "ISC","type": "module","dependencies": {}}Save the changes to your
package.jsonfile and run the start script we just defined.Terminal window npm run starttest-project@1.0.0 startnode index.js:3c ~nyaaAdding script commands in
package.jsonwill make your life much easier: you don’t need to remember the specific file names of every different file you want to run and it actually allows you to run multiple scripts at once as a single program. Script commands tend to have standard names likenpm run startornpm run devso they’re much easier to remember than individual file names.
For this exercise, we’re going to practice with Cat ASCII faces.
-
In the command line, run
npm install cat-ascii-faces.Terminal window npm install cat-ascii-facesadded 8 packages, and audited 9 packages in 5sfound 0 vulnerabilitiesThe
npm install [package-name]command adds a new package from npmjs.com to your project. To find the online home of a package you can type the name into the search or create the url yourself by adding/package/and the package’s name, e.g.npmjs.com/package/cat-ascii-faces.If it didn’t happen during the initialization step, then your
node_modules/folder andpackage-lock.jsonfile should have been created.Directory/
DirectoryUsers/
Directoryboba-tan/
Directorynpm-shenanigans/
Directorynode_modules/
- cat-ascii-faces
- …
- package.json
- package-lock.json
- index.js
If you look at your
package.jsonfile, you’ll notice your new dependency has been added!package.json {"name": "npm-shenanigans","version": "1.0.0","description": "A project to practice our NPM skills!","main": "index.js","scripts": {"test": "echo \"Error: no test specified\" && exit 1","start": "node index.js"},"author": "boba-tan","license": "ISC","type": "module","dependencies": {"cat-ascii-faces": "^2.0.0"}} -
Edit your code to use our new dependency
In your
index.jsfile, edit your code like this:index.js import getRandomCatFace from "cat-ascii-faces";console.log(":3c ~nyaa")console.log(getRandomCatFace());The first line in the code imports a specific function (
getRandomCatFace()) from thecat-ascii-facesnpm package.In the other line we added, we’re calling the function we imported inside a
console.log()to display a random ASCII cat face in our console.Save the changes in your
index.jsfile. -
Run the
startscriptBecause of the code we added to
index.jsin the previous step, using node to run this file will now output a random ASCII cat face to our console.Terminal window npm run start(.=^・ェ・^=)
Let’s get you familiar with NPM and code packages without needing to do any coding yourself. All you need is your command line and a bit of curiosity to check out how package files are organized.
-
Download an existing project from the web.
Go to GitHub or a similar site and find a project that already includes a
package.jsonfile. To find out how to get this project onto your own device see our guide on git clone. (TODO: add link)Here’s what your new cloned project’s folder might look like:
Directory/
- …
DirectoryUsers/
Directoryboba-tan/
- …
Directorystarter-project/
Directoryimages/
- …
Directorytests/
- …
- README.md
- index.js
- index.html
- package.json
- LICENSE
-
Install the project’s dependencies.
In your terminal use the
cdcommand to navigate into the project folder and runnpm installto download the project’s dependencies.Terminal window cd starter-projectnpm installadded 176 packages, and audited 177 packages in 23s33 packages are looking for fundingrun `npm fund` for details2 low severity vulnerabilitiesSome issues need review, and may require choosinga different dependency.Run `npm audit` for details.Once
npm installis done running (might take a while!) you’ll see a few differences in your project folder: a new file calledpackage-lock.jsonand anode_modules/folder.Directory/
DirectoryUsers/
Directoryboba-tan/
Directorystarter-project/
Directorynode_modules/
- …
Directoryimages/
- …
Directorytests/
- …
- index.js
- README.md
- index.html
- package.json
- package-lock.json
- LICENSE
-
Check for existing scripts.
Find out what scripts are available in the project you cloned by looking at the script section of
package.json. -
Choose a script to run.
Use the listed commands to run your code via your command line. Most often, you’ll find
npm run startornpm run devto run the main program itself. Depending on the project there might be other scripts likelintortest. Run a few different ones and see if you can figure out what they do!<screenshot of command line>
-
Take a look at your
node_modules/folder.You’ll notice there’s a lot of packages in there already! All the current dependencies for the project will have been automatically installed by
npm install, which you ran during the initialization step. -
Add a new dependency.
If you want, you can add new dependencies to the project with
npm install [package-name]ornpm i [package-name]. When you install a new package there’s no need to re-runnpm install.
You’ve successfully used the most important NPM commands and seen how they work in practice: you know how to start a new project, add code packages to it, and run your code using scripts; you also know how to get an existing project up and running by installing its dependencies; and, if you need a refresher on how to do either, you know where to go for answer!
Now, it’s tiem to use what you learned in your own web projects (past and future), or find some NodeJS projects to contribute to.
We suggest to:
- Check out this tutorial to start building your very own Astro blog!
- Install
@fujocoded/ao3.js, and come help us build it. It’s a great way to learn NodeJS! - Browse the NPM registry website, and discover new libraries. What do you wish you could do with your code?