Modules & npm/package.json
📦 Modules & npm/package.json
🧩 The Module System: CommonJS
Node.js uses CommonJS modules. A module is just a JavaScript file that exports code for other files to use.
module.exports
What a module shares. Can be a function, object, class, or anything else.
require()
Load a module. Returns what the module exported.
Local Modules
require('./path') — load a file in your project.
Installed Packages
require('lodash') — load an npm package.
📥 npm: Package Manager
npm is Node's package manager. It lets you:
- Download and install packages (libraries) that others have written
- Manage versions of packages your project depends on
- Publish your own packages for others to use
- Run scripts defined in package.json
Installing a Package
📄 package.json: Your Project's Config
package.json is a JSON file that describes your project and its dependencies.
name & version
Package identity. Follows semantic versioning (1.0.0 = major.minor.patch).
scripts
Commands you can run: npm start, npm test, npm run dev.
dependencies
Packages your app needs to run (installed in production).
devDependencies
Packages only needed for development (testing, linting, bundling).
🆕 Creating package.json
Interactive Setup
Quick Setup (use defaults)
🔢 Semantic Versioning (Semver)
Versions follow the pattern MAJOR.MINOR.PATCH (e.g., 1.5.3):
- 1.0.0 — Breaking changes (incompatible API)
- 1.5.0 — New features (backward compatible)
- 1.5.3 — Bug fixes (backward compatible)
Version Constraints in package.json
Exact Version
Flexible Version
💻 Coding Challenges
Challenge 1: Create & Use Modules
Create a utils.js module that exports functions for validation (email, phone number). Create app.js that requires and uses these functions.
Goal: Practice module creation and require().
Challenge 2: npm & package.json
Initialize a new Node.js project with npm init. Install lodash and express. Add a custom npm script that echoes "Hello from npm script". Run it.
Goal: Get comfortable with npm and package.json.
Challenge 3: Exporting Different Types
Create modules that export: a function, an object, a class, and a constant. From app.js, require each and use them in different ways.
Goal: Understand that module.exports can be anything.
After you npm install packages, a huge node_modules/ folder is created. Don't commit this to git — add it to .gitignore. When cloning a repo, just run npm install and it recreates node_modules from package.json. This keeps your repo small and reproducible.
🎯 What's Next
Now that you can organize code with modules and manage packages with npm, we'll explore Callbacks & Promises — diving deeper into async patterns beyond setTimeout.