CodeBlanks Logo Icon CodeBlanks

package.json scripts

Learn to define commands with package.json scripts.

package.json scripts

The scripts section is where you define frequently used commands with short names. When you write "scripts": { "dev": "nodemon server.js" } in package.json, you run that command with npm run dev.

Two scripts are special: start and test. They run with npm start and npm test; the word run is not needed. All other scripts are called as npm run <name>, for example npm run build or npm run lint. This way you run long commands through short names, and your teammates use the same commands.

Built-in scripts

start and test are npm's built-in scripts. They run directly with npm start and npm test; no run is needed.

For example, if you define "scripts": { "start": "node server.js", "test": "jest" }, then npm start launches the server and npm test runs the tests. Other scripts (dev, build, lint) require npm run <name>. This distinction provides a shortcut for the two most common commands. You can also define scripts that run before or after another script using the pre and post prefixes; for example pretest runs before the tests.

Practice Print the start script value

Define a string named content with the value {"name":"my-app","scripts":{"start":"node server.js","dev":"nodemon server.js"}}. Parse it into an object with JSON.parse. Print pkg.scripts.start with console.log.

Starter code

index.js
// Define the package.json content (with a scripts field)
// Parse it into an object with JSON.parse
// Print the start script value
// write here

Sample solution

index.js
const content = '{"name":"my-app","scripts":{"start":"node server.js","dev":"nodemon server.js"}}';
const pkg = JSON.parse(content);
console.log(pkg.scripts.start);

Expected output

node server.js

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the run command

Question
npm ____ dev
Answer
npm run dev

Explanation: npm run dev runs a custom script.

2 Match each command to its trigger

Term Meaning
npm start Runs the start script
npm test Runs the test script
npm run dev Runs the dev script
npm run build Runs the build script

3 Which command runs a custom 'dev' script?

index.js
npm run dev
  • npm dev
  • npm start dev
  • npm run dev Correct answer
  • npm run start

Explanation: Custom scripts run with npm run <name>.

All lessons in Intermediate