Skip to content

Instantly share code, notes, and snippets.

@rpivo
Last active December 14, 2020 21:11
Show Gist options
  • Save rpivo/3816cc5a085634fc682310a05e93535f to your computer and use it in GitHub Desktop.
Save rpivo/3816cc5a085634fc682310a05e93535f to your computer and use it in GitHub Desktop.
Using NPM's Pre & Post Scripts

Using NPM's Pre & Post Scripts

NPM has some powerful built-in scripts that can be used inside a package.json file. Scripts have built-in pre and post lifecycle hooks that help you control these processes to some degree. If the process(es) are more complicated, this may be too simplistic for your needs, but it's nice to know that they're available.

You can do something like this:

  "scripts": {
    "prestart": "echo 'preparing build...'",
    "poststart": "echo 'process finished.'",
    "start": "rollup -c"
  }

This is pretty contrived, but you'll get preparing build... before Rollup compiles your build, and then process finished. after compilation finishes when you run the start script.

A common scenario might be to build your code prior to publishing:

  "scripts": {
    "prepublishOnly": "rollup -c",
  }

(prepublish was deprecated in favor of prepare, and it runs before a variety of different scenarios. Use prepublishOnly to run a script prior to publishing only).

Something that's really neat is that you can use any custom string for a script, and the pre and post versions of that script will work. For instance:

  "scripts": {
    "prefoo": "echo 'preparing build...'",
    "postfoo": "echo 'process finished.'",
    "foo": "rollup -c"
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment