In this lab, you'll learn how to initialize a project with a package.json file, install dependencies, define custom scripts, and leverage various npm commands.
Follow along with each step and try out the commands in your terminal.
Lab Workflow: Using npm as a Development Tool
1. Introduction to npm and package.json
npm (Node Package Manager) is the default package manager for Node.js. It allows you to:
Install third-party libraries (dependencies) to your project. Manage your project’s metadata and dependencies via the package.json file. Create custom scripts to automate development tasks (e.g., starting the server, running tests, linting, etc.). The package.json file is the heart of your project. It contains important information such as the project name, version, scripts, dependencies, and more.
2. Setting Up Your Project
Step 2.1: Initialize a New Project
Open a terminal and navigate to your project directory. Run the following command to create a new package.json file interactively: This command will ask you several questions (name, version, description, entry point, test command, Git repository, keywords, author, license).
You can press Enter to accept the defaults or type in your custom values. Tip: If you want to quickly generate a package.json with default values, run: Step 2.2: Explore the package.json File
Open the newly created package.json file. Notice the following directives:
name: The name of your project. version: Your project's version. description: A brief description of your project. main: The entry point of your application (e.g., server.js or index.js). scripts: Commands you can run using npm (e.g., npm start, npm test, etc.). dependencies: Libraries required to run your application. devDependencies: Libraries needed during development (e.g., testing libraries, linters). 3. Installing Dependencies
Step 3.1: Add a Dependency
Suppose you want to install Express as a dependency. Run:
This command will:
Download and add Express to the node_modules folder. Update your package.json file under the "dependencies" section. Create or update the package-lock.json file, which locks your dependency versions. Step 3.2: Add a Dev Dependency
For development-only tools (like nodemon for automatic server restarts), run:
npm install nodemon --save-dev
This adds nodemon to the "devDependencies" section in your package.json.
4. Understanding and Using Scripts in package.json
The "scripts" section in package.json lets you define custom commands. For example, your package.json might include:
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "echo \"Error: no test specified\" && exit 1"
}
Step 4.1: Running Scripts
This command executes the start script defined in your package.json. Start in Development Mode:
Run: The run keyword is required for any script that isn’t start or test (with some exceptions). Running a Test Script:
Run: This executes the test script (by default, it might just output an error message until you define your tests). Step 4.2: Customizing Scripts
Feel free to add or modify scripts to automate tasks such as:
Linting:
If you install a linter (e.g., ESLint), you could add: Building:
For transpiling or bundling your code, you might add: "build": "webpack --mode production"
Then run the script using:
npm run lint
npm run build
5. Other Useful npm Commands
5.1: Updating Dependencies
To check for outdated packages, run:
To update a specific package, run:
npm update <package-name>
5.2: Uninstalling Dependencies
To remove a dependency, run:
npm uninstall <package-name>
This command removes the package from both the node_modules folder and the package.json file.
5.3: Running npm Audit
To check for known vulnerabilities in your dependencies, run:
To attempt automatic fixes, run:
5.4: Clearing the Cache (if needed)
If you run into issues with npm, sometimes clearing the cache can help:
6. Lab Exercise: Putting It All Together
Initialize a New Project: Create a new directory for your project. Run npm init -y to quickly generate a package.json. Run npm install express to add Express. Run npm install nodemon --save-dev to add nodemon as a dev dependency. Open package.json and update the "scripts" section to include: "scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
}
Create a file named server.js with the following content: const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send('Hello, npm workflow!');
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
In the terminal, run npm run dev to start the server using nodemon. Open your browser and navigate to http://localhost:3000 to see the message. Modify the server code and save changes to see nodemon automatically restart the server. Try adding a new script (e.g., "hello": "echo Hello World") in package.json and run it with npm run hello. 7. Summary
In this lab, you learned how to:
Initialize a Node.js project with npm init. Install dependencies and devDependencies. Understand the structure and directives in package.json. Create custom npm scripts and execute them. Use npm commands to manage, update, and secure your project dependencies. By mastering these npm tools and workflows, you’ll streamline your development process and keep your projects well-organized.
Here is an extended lab workflow that not only teaches you how to use npm as a development tool but also dives deep into the key stanzas (sections) in your package.json file.
Each section includes explanations, examples, and hands-on exercises that you can try in your own projects.
Lab Workflow: Using npm and Understanding package.json Stanzas
In this lab, you’ll learn how to use npm to manage your Node.js project and how to work with the various stanzas in your package.json file. We’ll cover the following areas:
1. Project Metadata Stanza
The top section of your package.json contains general information about your project. Key fields include:
name: The name of your project. This should be lowercase and URL-friendly. version: The current version of your project following . description: A brief description of what your project does. main: The entry point file of your project (often server.js or index.js). repository: The location of your project’s source code (e.g., GitHub URL). keywords: An array of strings that describe your project. author: The name (and optionally email) of the project’s author. license: The license under which your project is released (e.g., MIT). Example
{
"name": "my-awesome-project",
"version": "1.0.0",
"description": "An example project to demonstrate npm and package.json stanzas",
"main": "server.js",
"repository": {
"type": "git",
"url": "https://github.com/yourusername/my-awesome-project.git"
},
"keywords": ["nodejs", "npm", "example"],
"author": "Your Name <you@example.com>",
"license": "MIT"
}
Exercise 1
Initialize a new project:
Open your terminal and run: Edit the generated package.json: Change the "name" to "npm-lab-project". Update the "version" to "0.1.0". Add a "description" field with a short summary of your project. Add a "keywords" array with at least three relevant terms. 2. Dependencies and DevDependencies Stanzas
These stanzas manage the external libraries your project needs.
dependencies: Packages required for your application to run.
Installed with: npm install <package-name>
devDependencies: Packages needed only during development (such as testing frameworks, linters, or tools like nodemon).
Installed with: npm install <package-name> --save-dev
Example
After installing Express and nodemon, your package.json might include:
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"nodemon": "^2.0.20"
}
Exercise 2
Install Express as a dependency: Install nodemon as a development dependency: npm install nodemon --save-dev
Verify:
Open package.json and ensure that the "dependencies" and "devDependencies" stanzas reflect your installed packages. 3. Scripts Stanza
The "scripts" stanza allows you to define custom commands for common tasks. Some default scripts include:
start: Typically used to start your application. test: Runs your test suite. You can add any custom scripts that suit your development workflow.
Example
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"test": "echo \"No tests specified\" && exit 0",
"build": "webpack --mode production",
"lint": "eslint ."
}
How to Run Scripts
Run the default start script: Run a custom script (like dev): If you’ve defined a test script, run: Exercise 3
Add custom scripts:
In your package.json, add or update the "scripts" stanza to include: A "start" script that runs your main file (e.g., node server.js). A "dev" script that runs nodemon (e.g., nodemon server.js). A custom script "hello" that prints “Hello, npm lab!” to the console using an echo command. "scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"hello": "echo \"Hello, npm lab!\""
}
Run npm run hello and verify the message. Start your server using npm run dev. 4. Additional Useful Fields
While the metadata, dependencies, and scripts are the most commonly used stanzas, there are additional fields that can help further configure your project:
engines: Specify the versions of Node.js (and npm) your project supports. "engines": {
"node": ">=14.0.0",
"npm": ">=6.0.0"
}
bugs: Provide a URL where issues can be reported. "bugs": {
"url": "https://github.com/yourusername/npm-lab-project/issues"
}
config: Custom configuration options for your scripts. "config": {
"port": "3000"
}
These fields are optional but can be very useful in a collaborative or production environment.
Exercise 4
Add an engines stanza:
Update your package.json to include an "engines" field that specifies Node.js version 14 or later. Add a bugs URL:
Include a "bugs" field with a URL where users can report issues. Save your changes and review your package.json to see how these additional stanzas integrate with the rest of your configuration. 5. Exercises Summary
To wrap up the lab, complete these exercises:
Initialize and Modify Project Metadata: Update fields: "name", "version", "description", and "keywords". Install a runtime dependency (e.g., Express). Install a development dependency (e.g., nodemon). Verify that these appear correctly in the appropriate stanzas. Add or modify scripts in the "scripts" stanza (e.g., "start", "dev", "hello"). Run your custom scripts to see them in action. Enhance package.json with Additional Fields: Add "engines" and "bugs" stanzas. Optionally, add a "config" stanza for custom settings.