NPM and package.json in Node.js: Setup, Scripts, Dependencies, and SemVer

Build a small Node.js project from an empty folder, install Lodash, add reusable npm scripts, compare the manifest and lockfile, and practise SemVer ranges.

KnowledgeGate Team

Exam prep & CS education

Updated 12 Nov 20266 min read
NPM and package.json in Node.js: Setup, Scripts, Dependencies, and SemVer

npm, package.json, package-lock.json, and node_modules appear together, but each solves a different problem. Start in an empty folder, install a package, create a repeatable script, and read common version ranges. npm is lowercase in commands and official documentation, although learners often search for “NPM”. The Node.js Tutorial: The Complete Learning Path from Zero to Job-Ready orders runtime, core modules, Express and data work. Package setup is the narrower task: take one small project from npm init to a reproducible npm ci.

1. NPM, Node.js, and package.json: what each one does

Node.js runs JavaScript outside the browser. npm installs project packages and runs named scripts. package.json is the project manifest, package-lock.json records the resolved dependency tree, and node_modules contains the files installed on your machine.

The official npm package.json documentation defines how npm interprets manifest fields. A limited analogy is this: package.json is a shopping list and rule sheet, the lockfile is the itemised receipt with exact versions, and node_modules is what arrived. The manifest also stores scripts and metadata.

Suppose a Git project includes package.json and package-lock.json, but not node_modules. With a consistent lockfile, npm ci reconstructs a clean installation. This matters in a backend and full-stack context with teammates or automated builds.

2. Create the project with npm init

Run these commands in a terminal:

bash
mkdir kg-npm-demo
cd kg-npm-demo
npm init -y
npm pkg set type=module
npm pkg set scripts.start="node index.js"
npm pkg set scripts.check="node --check index.js"

mkdir creates the folder, and cd enters it. npm init -y creates the manifest with npm's defaults; use interactive npm init to choose values yourself. The npm pkg set commands add the module type and two scripts.

The relevant result is:

json
{
  "name": "kg-npm-demo",
  "version": "1.0.0",
  "type": "module",
  "scripts": {
    "start": "node index.js",
    "check": "node --check index.js"
  }
}

Read six fields for now. name identifies the project, version records its version, type controls the module format, and scripts names reusable commands. dependencies records runtime packages; devDependencies records development tools. "type": "module" makes this package's .js files use ES module syntax. CommonJS vs ESM in Node.js: Modules Tutorial with Runnable Examples explains module markers, loading semantics, interoperability and migration; this package uses ESM only to keep the Lodash program consistent.

3. Install one dependency and run a real program

Install a deliberately pinned Lodash release:

bash
npm install lodash@4.18.1 --save-exact

The exact pin keeps the exercise reproducible. npm documents that --save-exact records an exact version instead of its default range operator. The command adds "lodash": "4.18.1" under dependencies and updates package-lock.json.

Create index.js exactly as follows:

js
import lodash from "lodash";

const orders = [
  { id: "A101", amount: 199 },
  { id: "A102", amount: 349 },
  { id: "A103", amount: 452 },
];

const total = lodash.sumBy(orders, "amount");
console.log(`Order total: ${total}`);

Now run npm start. Lodash reads each amount and sums the values:

Code
199 + 349 + 452 = 1000
Order total: 1000

Lodash makes the installed package observable; simple addition does not need a library. To continue with Express and MongoDB, use the NodeJs + ExpressJs + MongoDB course.

4. package.json vs package-lock.json vs node_modules

The same Lodash installation appears differently in three places:

Artefact

What this example contains

Purpose

package.json

"lodash": "4.18.1"

Declares the direct dependency intent

package-lock.json

node_modules/lodash resolved to 4.18.1, with resolution and integrity data

Captures the resolved tree

node_modules/lodash

Installed package files

Supplies the code loaded at runtime

Do not reproduce or hand-edit the full lockfile. Use npm install to change dependencies. Use npm ci for a clean, lockfile-driven installation in a clone or CI job. npm requires an existing lockfile; if its declarations disagree with package.json, npm ci exits instead of rewriting it.

Commit package.json and package-lock.json. Normally, add node_modules to .gitignore because npm can reconstruct it.

Dependency flow from package.json and package-lock.json to installed Lodash 4.18.1 files, with npm ci reproducing the project and its 1000 total.

5. Read dependency versions with SemVer

Semantic Versioning uses MAJOR.MINOR.PATCH. In 2.4.1, 2 represents incompatible API changes, 4 represents backward-compatible functionality, and 1 represents backward-compatible fixes. npm documents these meanings, but maintainers do not always apply SemVer perfectly.

Assume only these releases exist: 2.4.1, 2.4.7, 2.5.0, 2.9.3, and 3.0.0.

Declaration

Eligible interval

Selected from the set

2.4.1

Exact version only

2.4.1

~2.4.1

>=2.4.1 <2.5.0

2.4.7

^2.4.1

>=2.4.1 <3.0.0

2.9.3

None of the three declarations selects 3.0.0. The --save-exact option records one Lodash version, not an update range. One zero-major warning: ^0.2.3 means >=0.2.3 <0.3.0, while ^0.0.3 means >=0.0.3 <0.0.4. A caret stops before the leftmost non-zero component changes, so zero-major ranges are intentionally narrower.

Horizontal SemVer number line shows exact 2.4.1, tilde range below 2.5.0 with 2.4.7, caret range below 3.0.0 with 2.9.3, and red 3.0.0 outside.

6. Turn repeated commands into npm scripts

Extend the manifest's scripts to this exact object:

json
{
  "scripts": {
    "start": "node index.js",
    "check": "node --check index.js",
    "verify": "npm run check && npm start",
    "dev": "nodemon index.js"
  }
}

Run npm run verify. When syntax is valid, node --check produces no success text, then npm start prints Order total: 1000. Run npm run to list available scripts.

Add the development tool with:

bash
npm install --save-dev --save-exact nodemon@3.1.14

Lodash 4.18.1 stays under dependencies because the application imports it at runtime. Nodemon 3.1.14 belongs under devDependencies because it assists development. These fields express dependency intent.

Interview or lab check: Why prefer npm run verify over asking every team member to remember two commands? The named script provides one version-controlled project command. It does not make the underlying commands faster.

7. Fix common npm and package.json errors

Symptom

Likely cause

Check

Fix

EJSONPARSE after an edit

A trailing comma makes the file invalid JSON

Inspect the line reported and validate strict JSON

Remove the trailing comma and save valid JSON

Missing script: "start"

The script key is absent or misspelled

Run npm run

Restore the exact start key

ERR_MODULE_NOT_FOUND for lodash

Dependencies are not installed

Check for node_modules/lodash

Run npm ci with a valid lockfile, otherwise run npm install

ReferenceError: require is not defined in ES module scope

require("lodash") is used while "type": "module" is active

Inspect the module type and import line

Restore import, or deliberately use a .cjs file and matching script for CommonJS

Never edit node_modules, and do not delete the lockfile merely to silence a mismatch. A global installation does not declare a project dependency. Check package names, review packages, and read relevant advisories. npm does not eliminate package risk.

8. Check understanding, then choose the next step

  1. Replace the order amounts with 125, 375, and 625. Predict the output.

  2. From the supplied release set, predict the selections for ~2.4.1 and ^2.4.1.

  3. Replace the import with const lodash = require("lodash") while "type": "module" remains active. Observe the failure, then restore the import.


Answers: The first total is 125 + 375 + 625 = 1125, so the output is Order total: 1125. The tilde range selects 2.4.7, while the caret range selects 2.9.3. The third exercise produces a require is not defined failure because the .js file is an ES module.

Which files should be committed after installing Lodash? The beginner answer is the source files, package.json, and package-lock.json, not node_modules.

The manifest declares intent, the lockfile captures resolution, node_modules holds installed code, scripts standardise commands, and SemVer ranges control eligible updates. Use the Coding Skills category to place this package workflow inside a broader web-development route.

Finish the complete kg-npm-demo, make a fresh copy without node_modules, run npm ci and npm run verify there, then continue with Mongoose schemas, models, validation, and population when you are ready to add a MongoDB data model.