Skip to content

Apologies for the appearance of the site. I'm designing in public!

A landscape of a lake between two hills

Pre- and Post- NPM Scripts

Published on Monday, 4 January 2021.
At 199 words, this article should take about 1 minute to read.
This article is more than 2 years old.

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?


Fin

Comments

In almost all cases, the comments section is a vile 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 Mastodon (which is not a vile cesspool of Reply Guys, racists, and bots).

onward-journeys module