There are many magic scripts available for use by the Node Package Manager ecosystem, that beginners yet don't use.
When I wanted to publish a package, I would manually bump the version, build the project, and then run npm publish
to ship the package. Which by itself took a lot of time.
But then, I read this documentation by npm and realized that all the processes can be automated and can be done in just one command.
The documentation has a lot going on, so in this DEV post, I'll try to demystify the 5 most important package.json scripts using the documentation as a reference.
"scripts": {
"prepublish": "minify or build your code here",
}
This command is run BEFORE the package is packed and published. This command also runs when user runs npm i
locally without any parameters and arguments.
From the NPM Docs:
If you need to perform operations on your package before it is used, in a way that is not dependent on the operating system or architecture of the target system, use a prepublish script.
Prepublish script includes tasks such as:
The advantage of doing these things at prepublish time is that they can be done once, in a single place, thus reducing complexity and variability.
Additionally, this means that:
coffee-script
as a devDependency
, and thus your users don’t need to have it installed.curl
or wget
or other system tools on the target machines.There is a little difference between prepare
and prepublish
...
prepare
script runs when git
dependencies are being installed. This script runs after prepublish
and before prepublishOnly
.
Example 👇
"scripts": {
"build": "rollup -c",
"prepare": "npm run build"
}
Building the project could be the best thing you can execute in the prepare
script.
This command serves the same purpose as prepublish
and prepare
but runs only on npm publish
! 🔥
As the name suggests, the command runs after npm publish
...
pre
ing and post
ing of scriptsTake a look at the below scripts.
"scripts": {
"predeploy": "cd example && npm install && npm run build",
"deploy": "gh-pages -d example/build"
}
To execute deploy
completely, you don't need to npm run predeploy && npm run deploy
, just running npm run deploy
will do the pre
and post
task.
You can add the pre
and post
prefixes to any script and have it run chronologically.
The names are pretty self-explanatory.
To read more about these, you can refer the NPM Docs about npm-scripts
.
The NPM Magic Scripts can prove useful to anyone and everyone. I regret not using it for my past projects. 😅