package.json: the fields that matter
A folder becomes a package when it holds a package.json: the file that names the folder, gives it a version, says which file a require of the package loads and which commands belong to it. npm reads the file before every install and every run, and Node.js reads it before it decides how to load a .js file.
The lesson starts from the file npm init -y writes and then sets the five fields that matter. One program prints them, a second requires the package by its own name and shows the entry file, and a third shows what "type": "module" does to a file that still calls require.
npm init -y
npm init -y answers every question with a default: the name of the folder becomes the package name, the version starts at 1.0.0, and the only script is a test that fails until somebody writes one. npm 11 writes the field "type": "commonjs" on its own, which is the default of the runtime made explicit.
The command prints the path of the file it wrote and the file itself. The first line belongs to this machine, so the file is shown on its own:
mkdir package-course
cd package-course
npm init -y
{
"name": "package-course",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"type": "commonjs"
}
The file is valid but says nothing about the package: the description, the keywords and the author are empty, the entry file index.js does not exist, and the test script is a placeholder that exits with the status 1. The next section fills the fields a program and npm read.
The five fields
name is what require and npm install use, and it has rules: lowercase, no spaces, one name for the whole registry. version is the number npm compares when it resolves a range, and the lesson on ranges comes back to it. type chooses the module system for .js files, main names the file a require of the package loads, and scripts is the table behind npm run.
The file of this lesson replaces the placeholder with two scripts: one starts the program and one runs the first program of the page.
The file package.json:
vi package.json
{
"name": "package-course",
"version": "1.0.0",
"description": "A page that reads its own package.json",
"type": "commonjs",
"main": "lib/index.js",
"scripts": {
"start": "node app.js",
"fields": "node fields.js"
},
"keywords": [
"javascript",
"npm"
],
"author": "Arthur Isaev",
"license": "ISC"
}
npm can read the fields itself. npm pkg get takes the names of the fields and prints their values as JSON, which is the shortest way to check what a command such as npm version or npm pkg set changed.
npm pkg get name version main
{
"name": "package-course",
"version": "1.0.0",
"main": "lib/index.js"
}
A program reads the same file with JSON.parse, because that is the only way it can see its own package: there is no package object in the runtime, only the file. The program prints the five fields and the first script.
The file fields.js:
const { readFileSync } = require('node:fs');
const pkg = JSON.parse(readFileSync('package.json', 'utf8'));
console.log('name:', pkg.name);
console.log('version:', pkg.version);
console.log('type:', pkg.type);
console.log('main:', pkg.main);
console.log('the scripts:', Object.keys(pkg.scripts).join(', '));
console.log('start runs:', pkg.scripts.start);
node fields.js
name: package-course
version: 1.0.0
type: commonjs
main: lib/index.js
the scripts: start, fields
start runs: node app.js
Six lines and the file is summarised. A field that is missing reads as undefined and not as an error, which is why a program that depends on a field checks it before it uses it. The same program runs through npm run fields, and one word of the script table is enough to start it.
main and the entry file
main is the file that a require of the package loads. require('.') from a file in the folder and require('package-course') from a program that installed the package both ask this field, and without it Node.js tries index.js. The value may name a file in a subfolder, which is what a small library usually does, and it has no leading ./.
The program requires its own package by the dot, which is the folder itself, and prints the greeting it exported and the file the lookup found.
The file lib/index.js:
function greet(name) {
return `hello, ${name}`;
}
module.exports = { greet };
The file app.js:
const path = require('node:path');
const { greet } = require('.');
console.log(greet('reader'));
console.log('the entry file is:', path.relative(process.cwd(), require.resolve('.')));
node app.js
hello, reader
the entry file is: lib/index.js
require.resolve answers the absolute path of the entry file, and path.relative turned it into the value of the field with no folder in front of it. Change the field to lib/message.js and the same command fails with MODULE_NOT_FOUND, because the file it names does not exist; the next lesson follows the same lookup into node_modules.
type and the module system
type has two values. commonjs, and also no field at all, makes a .js file CommonJS: require, module.exports and __dirname work. module makes every .js file of the folder an ES module: import, export and import.meta, and no require at all.
The second folder of the lesson changes the field and keeps one file of each kind beside the other. The manifest is short, because the module system is the only thing it is about.
mkdir esm-course
cd esm-course
npm init -y
vi package.json
{
"name": "esm-course",
"version": "1.0.0",
"type": "module",
"main": "lib/index.js"
}
The file lib/index.js:
export function greet(name) {
return `hello, ${name}`;
}
The file app.js:
import { greet } from './lib/index.js';
console.log(greet('reader'));
console.log('this file is a module:', import.meta.url.endsWith('app.js'));
node app.js
hello, reader
this file is a module: true
The extension .cjs overrides the field, which is the escape hatch for an old file inside a module package. The same CommonJS code saved as old.cjs still runs.
The file old.cjs:
const { greet } = require('./lib/index.js');
console.log(greet('reader'));
node old.cjs
hello, reader
Copy it to a .js name and the field decides: node reads the file as a module, and the call to require fails before anything runs. The block below is the real message with the folder of this machine replaced by a dot and the stack frames left out.
cp old.cjs old.js
node old.js
rm old.js
file://./old.js:1
const { greet } = require('./lib/index.js');
^
ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and
'./package.json' contains "type": "module". To treat it as a CommonJS script, rename it
to use the '.cjs' file extension.
The last two lines of the message name the cause and the fix, which is rare enough in a runtime error to be worth reading twice. A package that adds "type": "module" has to rename its CommonJS files or rewrite them; a package that leaves the field alone keeps every file as it is, and the lesson on modules covers what the two systems share.
Exercises
- Create a folder whose name has a capital letter, run npm init -y and read the name field. Which characters of the folder name does npm keep?
- Remove the main field and run app.js. Which file does the require look for, and what does the program print?
- Add a script that prints the version with npm pkg get version and run it with npm run. Which field of the table names it?
- Print pkg.scripts.missing in fields.js. What does a program get for a script that does not exist, and what does npm answer instead?
- Change type to module in package-course and run fields.js. Which line fails first, and which extension would keep the file working?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
npm init -yuse as the package name?Answer
The name of the folder
The default answer to every question is the folder: its name, a version of 1.0.0 and one placeholder script.
-
What does this program print?
const pkg = { name: "notes", version: "2.1.0", main: "src/app.js" }; console.log(pkg.name, pkg.version);Answer
notes 2.1.0
The two fields are read from the object exactly as they were written.
-
Which two fields identify a package?
Answer
name and version
The registry compares the pair, and a range is resolved against the version of that name.
-
What does this program print?
const pkg = { scripts: { start: "node app.js", test: "node test.js" } }; console.log(Object.keys(pkg.scripts).join(" "));Answer
start test
The keys keep the order of the file, so the start script comes first.
-
What does the main field name?
Answer
The file that a require of the package loads
The resolver reads main and loads that file; without the field it tries index.js.
-
A .js file in a package with
"type": "module"calls require. What is the first line of the error?Answer
ReferenceError: require is not defined in ES module scope, you can use import instead
The file is parsed as a module, where require does not exist at all, so the call fails with a reference error.
-
What does this program print?
const pkg = { main: "lib/index.js" }; console.log(pkg.main.endsWith(".js"), pkg.main.startsWith("lib"));Answer
true true
The value ends with the extension and starts with the folder name, both without a leading dot.
-
What does
npm pkg get name versionprint?Answer
The values of the named fields as JSON
The command reads the file and prints the requested fields as a JSON object.
-
What does this program print?
const pkg = { name: "notes", keywords: ["npm", "json"] }; console.log(pkg.keywords.length, pkg.author);Answer
2 undefined
The array has two entries, and a field that the object does not have reads as undefined.
-
What does a package.json without a type field mean for a .js file?
Answer
It is CommonJS, so require and module.exports work
CommonJS is the default, and npm 11 writes the field only to make that explicit.
The programs on this page were run with Node.js 24.22.1 and npm 11.12.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev