New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Node.js› Modules and npm

Modules and npm

💻 Node.js

Split code into modules, install packages and use package.json scripts.

Lesson 2 of 9 Tutorial
0 of 9 completed

npm is the package manager that ships with Node. A package.json file records your project and its dependencies.

By the end of this lesson you can:
  • Create and use ES modules.
  • Install a dependency.
  • Add and run npm scripts.

Create a Project

Initialise a project and enable ES modules so import works everywhere.

mkdir my-api
cd my-api
npm init -y
npm pkg set type=module

Your Own Module

Export a function from one file and import it in another. Keep each file focused.

// maths.js
export function add(a, b) {
  return a + b;
}

// app.js
import { add } from "./maths.js";
console.log(add(2, 3));

Installing Packages

Install a dependency and record it in package.json. Use npm ci in deployment for a clean, locked install.

npm install express
npm install --save-dev nodemon
npm ci

Scripts

Put repeated commands in scripts so the whole team runs the same thing.

{
  "scripts": {
    "start": "node app.js",
    "dev": "nodemon app.js",
    "test": "node --test"
  }
}
Tip Commit package-lock.json. It pins exact versions so installs are reproducible.

Practice

  1. Initialise a project and create two modules.
  2. Install a package and inspect package.json.
  3. Add a dev script and run it with npm run dev.

Hands-on exercise

Create greet.js that exports greet(name).
Create app.js that imports it and prints greet('Amina').
Add an npm start script that runs app.js.

Recap

Modules split code into files, npm manages dependencies and scripts standardise common commands.

Example

mkdir my-api
cd my-api
npm init -y
npm pkg set type=module

Exercises

Exercise 1. A greeting module Easy
Create greet.js that exports greet(name).
Create app.js that imports it and prints greet('Amina').
Add an npm start script that runs app.js.
Node.js exercise-1.txt
Expected Output
Hello, Amina!

Lesson Nav

Lesson sections