Home

Run JavaScript Script Before Another Script

Automatically run scripts with NPM/Yarn before or after another script.

If you want to run a script before another one completes, you can do this by prepending pre to the script name. NPM (or Yarn) will automatically run the script.

Suppose I have a script called test that runs my test suite. But before I do that, I want to make sure a script called build runs first. I could have a configuration like this:

pacakge.json

{
"scripts": {
"build": "...",
"pretest": "build",
"test": "..."
}
}

Now when I run this command:

npm run test

The pretest script will automatically be run first, and in the example above, that means the build script automatically runs before the test script.

Note: Use post as the prefix to run a script after another script.

Let's Connect

Keep Reading

5 Reasons I'm Excited about Astro

Astro is the new static site generator on the scene. This is why I'm so excited about it.

Aug 24, 2021

Run JavaScript when Variable Exists

It's super frustrating to have a race condition in which some JavaScript code may be run before a variable it needs exists, causing an error. Here's one approach to getting around that.

Aug 21, 2020

Dynamically Add JavaScript and CSS Files to Your Website Using JavaScript

When you can't use a JavaScript or CSS concatenater, this method can be useful for adding scripts and styles to your site on the fly.

Aug 05, 2013