Modules and npm
💻 Node.jsSplit code into modules, install packages and use package.json scripts.
npm is the package manager that ships with Node. A package.json file records your project and its dependencies.
- 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=moduleYour 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 ciScripts
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"
}
}Practice
- Initialise a project and create two modules.
- Install a package and inspect package.json.
- 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
Create app.js that imports it and prints greet('Amina').
Add an npm start script that runs app.js.
Expected Output
Hello, Amina!