Skip to content
A landscape of a lake between two hills

Pre- and Post- NPM Scripts

Monday, January 4, 2021

At 343 words, this article should take about 2 minutes to read.

I've been working on a project at work recently that takes data from a CMS, builds into a React app, and bundles into an iOS app using CapacitorJS

{
  "scripts": {
    "build": "react-scripts build",
    "harvest": "node harvest.js",
    "copy": "npx cap copy ios"
  }
}

It would be tedious to keep running npm run harvest && npm run build && npm run copy every single time.

I guess I could make a special case build script…

{
  "scripts": {
    "build:ios": "npm run harvest && npm run build && npm run copy"
  }
}

I'm not a fan of long chains of commands and, it turns out, neither are NPM.

Introducing pre and post!

{
  "scripts": {
    "prebuild": "npm run harvest",
    "build": "react-scripts build",
    "postbuild": "npm run copy",
    "harvest": "node harvest.js",
    "copy": "npx cap copy ios",
  }
}

These suffixes can be added to any NPM script and will run automatically when you run the main script.

Now, whenever I npm run build, I get npm run harvest and npm run copy for free!

It saves my fingers, it stops me forgetting to copy my build folder to iOS, and it satisfies my compulsion for short, neat lines.

What could you do with this?

Comments

In almost all cases, the comments section is a cesspool of Reply Guys, racists, and bots.

I don't want to have to deal with that kind of hell so I don't have a comments section.

If you want to continue the conversation, you can always hit me up on Twitter (which is, in it's own way, a vile cesspool of Reply Guys, racists, and bots).

Thomas Banks

Thomas Banks

When I'm not building things for the internet, I take photos of stuff.
Loading Invisible Visible Navigation Close Arrow Info Online Online