npm & package.json
// npm init -y → creates package.json
// package.json controls your project:
{
"name": "my-app",
"version": "1.0.0",
"type": "module", // use ESM (import/export)
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "node --watch index.js",
"test": "jest"
},
"dependencies": {
"express": "^4.18.0" // production
},
"devDependencies": {
"jest": "^29.0.0" // development only
}
}
// Commands:
// npm install express — add dependency
// npm install -D jest — add devDependency
// npm install — install all from package.json
// npm run start — run script
// npm uninstall express — remove package
// npm list — list installed
CommonJS vs ES Modules
// CommonJS (default in Node.js without "type":"module"):
// Export:
module.exports = { add, PI };
// Import:
const { add, PI } = require("./math");
const express = require("express");
// ES Modules (with "type":"module" or .mjs):
// Export:
export const PI = 3.14;
export function add(a, b) { return a + b; }
export default class App {}
// Import (.js extension required in ESM!):
import App, { PI, add } from "./math.js";
import express from "express";
// Semver ranges:
"^4.18.0" // >= 4.18.0 < 5.0.0 (minor updates OK)
"~4.18.0" // >= 4.18.0 < 4.19.0 (patch updates only)
"4.18.0" // exact version
// Always commit package-lock.json
// Never commit node_modules — add to .gitignore
⚡ Key Takeaways
- npm init -y bootstraps a project — always start here
- dependencies = runtime; devDependencies = build/test tools
- CJS: require/module.exports; ESM: import/export
- Semver: ^ = minor/patch updates, ~ = patch only, exact = no updates
- package-lock.json ensures reproducible installs — always commit it
🎯 Practice Exercises
EXERCISE 1
Create a utils package: math.js with arithmetic functions, string.js with string helpers. Set up an index.js barrel file. Import everything into main.js.