liveBook · Manning

Package.json

As explained in Secrets of the JavaScript Ninja, Third Edition

package.json is a project manifest file that records package metadata, scripts, and dependencies for JavaScript package tools.

A Node.js project needs a place to record the packages it uses and the commands it runs. package.json is that project file. Run `npm init -y` to create one without answering prompts, or start with `{}` when all you need is dependency tracking. The generated metadata can wait if you do not intend to distribute the package. section 3.2.1 section 2.1.1

Two fields do most of the work in these projects:

  • `dependencies` lists installed top-level packages. For example, `npm install express@5` adds an Express entry that npm may write as a caret version range, such as `^5.1.0`. section 3.2.1 section 3.2.3
  • `scripts` names commands to run with `npm run <script>`. Installed package executables are available on a script’s PATH, so a `lint` script can simply run `eslint .`. section 3.3.1

A lint-and-build command

With `"scripts": {"lint": "eslint .", "build": "npm run lint && ./build.sh"}`, run `npm run build` to lint before invoking the build script. Use `npm run hello -- "And goodbye."` to append an argument to a script without having npm interpret it as its own option. Scripts named `test` or `start` also support the shorter `npm test` or `npm start` form. section 3.3.1

Do not mistake package.json for a complete snapshot of installed packages. Its version ranges leave room for updates; `package-lock.json` records exact versions throughout the dependency tree. On installation, npm uses the lockfile to recreate that tree in `node_modules`. Committing the lockfile, rather than `node_modules`, helps a team keep installations in sync. For a package consumed by other projects, a lockfile fixes the local development tree but does not fix the downstream project’s tree. section 3.2.3 section 3.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Works through creation, dependency entries, scripts, and the lockfile distinction; leaves full life cycle script rules to npm documentation.
Examples
Uses an Express installation, an ESLint lint script, and minimal manifests for TypeScript tooling.
What it assumes
Assumes command-line project setup while showing both generated and empty starting files.
What you can do after
Operate/configure it by recording dependencies, defining npm scripts, and distinguishing version ranges from locked installations.
How it connects
Connects npm, version ranges, package-lock.json, node_modules, and package executables.

Also explained in

Compare how 7 books explain package.json →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.