Skip to main content
Node.js Basics
CHAPTER 12 Beginner

Package.json and Dependencies

Updated: May 13, 2026
15 min read

# Node.js Package.json and Dependencies

Welcome to Chapter 12! In the previous chapter, we generated a package.json file using npm init. This file is the absolute core of every Node.js project. It acts as an instruction manual, a manifest, and a blueprint all rolled into one.

In this chapter, we will open up package.json, understand every piece of it, learn how to manage different types of dependencies, and write our own custom terminal commands.

---

1. Introduction

When you share your code with another developer (or upload it to a server for deployment), you do not send them your node_modules folder. It is simply too massive.

Instead, you send them your code and the package.json file. When they run npm install in their terminal, NPM reads the package.json file, looks at the list of "dependencies", and automatically downloads the exact correct versions of all the libraries your app needs to function.

---

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Read and understand the structure of a package.json file.
  • Understand Semantic Versioning (SemVer) rules (e.g., ^1.4.2).
  • Differentiate between dependencies and devDependencies.
  • Create and run custom NPM scripts using npm run.
  • Reproduce a project using npm install.

---

3. Beginner-Friendly Explanations

Dependencies vs DevDependencies

When you install a package, you can categorize it:
  • Dependencies: Packages your app *needs to run in production* on the server. (e.g., Express, Mongoose, UUID). Command: npm install <package>
  • DevDependencies: Packages you only need *during development* on your laptop. (e.g., Nodemon, testing libraries, code formatters). Your final production server doesn't need these. Command: npm install -D <package>

NPM Scripts

Instead of typing long commands in the terminal like node ./src/server/index.js, you can create shortcuts in package.json under the "scripts" section. You might create a shortcut named "start", and then simply run npm run start.

---

4. Syntax Explanation

Let's look at a typical package.json file.

```json id="ch12-json-1" { "name": "my-cool-app", "version": "1.0.0", "description": "A backend API for my portfolio", "main": "index.js", "scripts": { "start": "node index.js", "dev": "nodemon index.js" }, "author": "Jane Doe", "license": "ISC", "dependencies": { "chalk": "^4.1.2", "uuid": "^9.0.0" }, "devDependencies": { "nodemon": "^3.0.1" } }

123456789101112131415161718192021222324252627
**File Explanation:**
- **name & version:** Identifiers for your app.
- **main:** The entry point of your application.
- **scripts:** Custom terminal commands. 
- **dependencies:** Production packages.
- **devDependencies:** Development packages.

---

## 5. Real-world Examples

**The Cloning Workflow:**
Imagine joining a company. You download their massive backend repository from GitHub. You open it, and there is no `node_modules` folder! How do you run it?
1. Open the terminal in the folder.
2. Type `npm install`.
3. NPM reads the `package.json`, sees the 50 dependencies required, and spends 2 minutes downloading them all and creating the `node_modules` folder.
4. Type `npm run dev` to start the server based on their custom scripts.

This workflow is identical everywhere in the world.

---

## 6. Multiple Code Examples

### Example 1: Installing a DevDependency
Let's install `nodemon` locally for the project, rather than globally.

bash id="ch12-bash-1" # The -D flag means "save to devDependencies" npm install -D nodemon

12345
After running this, check your `package.json`. You will see `nodemon` listed under `"devDependencies"`.

### Example 2: Creating NPM Scripts
Open `package.json` and find the `"scripts"` object. Change it to this:

json id="ch12-json-2" "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "node app.js", "dev": "nodemon app.js", "sayhello": "echo Hello from NPM!" }

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
Now, in your terminal, you can run:
- `npm run sayhello` -> Prints "Hello from NPM!"
- `npm run dev` -> Starts nodemon tracking `app.js`

*Note: `"start"` is a special script. You can run it simply with `npm start` (no `run` needed).*

### Example 3: Semantic Versioning (SemVer)
Look at `"chalk": "^4.1.2"` in your dependencies. What do those numbers mean?
It follows **Major.Minor.Patch** versioning.
- **Major (4):** Breaking changes. Old code might stop working.
- **Minor (1):** New features added in a backward-compatible way.
- **Patch (2):** Bug fixes.

What does the caret **`^`** mean? It means: "If I run `npm install` in the future, it is safe to automatically update to newer Minor or Patch versions (like 4.5.0), but NEVER update to a Major version (like 5.0.0) because it might break my app."

---

## 7. Output Explanations

When you run `npm run dev`, NPM looks inside `package.json`, finds the key `"dev"`, extracts the value `"nodemon app.js"`, and executes that command in the terminal. It acts as an alias.

---

## 8. Common Mistakes

1. **Typographical errors in JSON:** `package.json` must be strictly valid JSON. If you miss a comma, or use single quotes `'` instead of double quotes `"`, NPM will completely break and throw an error.
2. **Missing `npm install`:** Downloading a project from GitHub and immediately typing `npm start` will fail with a "Module not found" error because you forgot to run `npm install` to download the `node_modules`.
3. **Installing production packages as Dev:** Accidentally typing `npm install -D express`. Express is required for the production server! If it's a devDependency, the server won't install it when deployed, and your app will crash in production.

---

## 9. Best Practices

- **Never modify `package-lock.json`:** This file is generated automatically. It locks in the exact sub-dependencies of your dependencies. Leave it alone!
- **Always use `npm start`:** Make sure your `"start"` script points to the main file that runs your server. Most deployment platforms (like Render or Heroku) will automatically run `npm start` when deploying your app.
- **Keep it clean:** Occasionally review your `package.json`. If you installed a package 3 months ago but are no longer using it in your code, run `npm uninstall <package>` to keep your bundle size small.

---

## 10. Exercises

1. Initialize a new project using `npm init -y`.
2. Install `colors` as a regular dependency.
3. Install `eslint` as a devDependency using `-D`.
4. Inspect `package.json` to verify they are in separate categories.
5. Create a script named `"magic"` that runs `echo 🪄 Magic Script!`. Run it in the terminal.

---

## 11. Mini Project: Project configuration setup

**Objective:** Set up a professional Node.js project environment from scratch, mimicking a real-world setup.

**Step 1:** Create project

bash mkdir pro-setup cd pro-setup npm init -y

1
**Step 2:** Install dependencies

bash npm install moment npm install -D nodemon

12
**Step 3:** Configure `package.json` scripts
Edit the `"scripts"` section in `package.json` to match this:

json "scripts": { "start": "node index.js", "dev": "nodemon index.js" }

1
**Step 4:** Create `index.js`

javascript id="ch12-mini-project" // index.js const moment = require('moment');

console.log("------------------------"); console.log("Server initialized..."); console.log(Current Time: ${moment().format('MMMM Do YYYY, h:mm:ss a')}); console.log("Listening for changes..."); console.log("------------------------"); ``

Step 5: Run the dev script Run npm run dev. Your terminal will start Nodemon, print the time, and wait. Open index.js, add another console.log, save the file, and watch the terminal automatically restart!

---

12. Coding Challenges

Challenge 1: Create an NPM script called "clean" that clears the terminal screen (using the command cls on Windows or clear on Mac/Linux) and then runs node index.js. (Hint: chain commands using &&, e.g., "clear && node index.js").

Challenge 2: Look at your package-lock.json file. It's huge! Search inside it for the word "moment". Notice how much extra data NPM stores to guarantee project stability.

---

13. MCQs with Answers

Q1: Which section of package.json holds packages only needed during development? A) dependencies B) devDependencies C) scripts D) devPackages Answer: B

Q2: How do you execute a custom script named "build" from package.json? A) npm build B) node run build C) npm run build D) npm execute build Answer: C

Q3: What does the 'Minor' number represent in Semantic Versioning (e.g., the '2' in 1.2.5)? A) Bug fixes B) Complete overhaul C) New backward-compatible features D) Security patches only Answer: C

Q4: What command reads the package.json and downloads all listed dependencies? A) npm download B) npm install C) npm update D) npm get Answer: B

---

14. Interview Questions

  1. 1. What is the difference between dependencies and devDependencies?
*Answer:* dependencies are required for the application to run in a production environment (like a web framework or database driver). devDependencies are only required for local development and testing (like linters, test runners, or nodemon), and are ignored during production deployment.
  1. 2. What is the purpose of package-lock.json?
*Answer:* While package.json specifies general version ranges (like ^1.4.0), package-lock.json locks in the *exact* version of the package and its entire tree of sub-dependencies. This guarantees that if a team of 5 developers runs npm install, they all get the exact same byte-for-byte node_modules folder.

---

15. FAQs

Q: Can I change the version numbers in package.json manually? A: You can, but it won't actually update the package until you run npm install again. However, it's safer to use the terminal: npm install package@latest will update it and change the json automatically.

Q: What happens if I delete node_modules by accident? A: Don't panic! Just open the terminal in that folder and run npm install. NPM will rebuild the entire folder perfectly based on your package.json.

---

16. Summary

  • package.json is the brain of your project configuration.
  • Dependencies are for production; DevDependencies (-D) are for local development.
  • The "scripts" block is used to create terminal shortcuts (like "dev": "nodemon server.js").
  • Run custom scripts using npm run <script-name>.
  • Semantic Versioning (Major.Minor.Patch) helps track the impact of package updates.

---

17. Next Chapter Recommendation

You now know how to build servers with http`, manage files, use modules, and install NPM packages. It is finally time to introduce the most important NPM package in the Node.js ecosystem. In Chapter 13: Express.js Introduction, we will install Express and see how it makes building web servers 100x easier!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·