npm Scripts & Lifecycle Hooks

Automate your workflows with package.json scripts and powerful pre/post lifecycle hooks.

Package Managers4 min readConcept 12 of 24

The scripts object

The scripts object in your package.json is a powerful task runner. It allows you to define custom command-line aliases for your project, such as "start": "node server.js" or "test": "jest --passWithNoTests".

You execute these custom scripts by typing npm run <script-name> in your terminal.

The hidden $PATH magic

The biggest advantage of npm scripts is that npm temporarily alters your system's $PATH environment variable during execution.

Before running the script, npm prepends node_modules/.bin/ to the $PATH. This means your script can simply call "build": "tsc" instead of typing out the full path "build": "./node_modules/.bin/tsc".

Once the script finishes, the $PATH is restored, keeping your global environment perfectly clean.

Lifecycle Hooks

npm scripts support automatic execution pipelines via **lifecycle hooks**. If you prefix any script name with pre or post, npm will automatically run them before or after the main script.

For example, if you have "prebuild": "eslint .", "build": "tsc", and "postbuild": "echo Done", running npm run build will sequentially execute:

1. prebuild (runs the linter)

2. build (compiles the code)

3. postbuild (prints success)

Lifecycle Pipeline Simulator

Trigger the npm run build command below. Watch how npm automatically intercepts the command to run prebuild and postbuild hooks in the correct sequence.

prebuild
MAIN
build
postbuild
Terminal
$npm run build

Remember this

  • npm scripts allow you to define command-line aliases for your project tasks.
  • npm temporarily augments the $PATH to include node_modules/.bin, allowing direct access to local binaries.
  • Prefixing a script with pre or post creates automatic lifecycle pipelines (e.g., prebuild -> build -> postbuild).
  • The postinstall hook runs automatically after installing dependencies and is a common attack vector for malware.

Done with this concept?

Mark it complete to track your progress. No login needed.