The script should preferably be written in TypeScript and run with ts-node. You don't want to end up wasting 3 hours on a typo in the object key, TypeScript can catch most of those human errors.
scripts/*.(js|ts)files are supposed to be running directly from the shell. So for reusable modules, better to put them into
Avoid importing files from
srcor other directories, the
scriptsdirectory should be self-enclosed. In this way you can separate the dependencies of the scripts to your web apps and cache the dependencies separately.
Avoid running other scripts with
exec('npm run *'),
exec('node scripts/*'), instead, export the reusable part of the "runee" script and call it programmatically in the "runner" script.
Keep it simple, don't try to accomplish too many tasks in one single script.
Organising the logic in a procedural way, meaning the code flow should be the same as the execution flow.
Don't create step functions that are only to be called once (except for a
Minimise the number of mandatory options, by assigning default values, but at the same time, those values can be overridden by options or env variables. Overall, favour a convention over configuration design principle.
Use commander.js to declare the options, validate the input and set default value etc, DON't handcraft your own arguments parsing logics.
Use yn to parse boolean env variables, and always do
if(yn(process.env.*) === true)not
Use the execa to execute shell commands.
process.env.CIto tell if the script is running in CI, no need to add an option for that.
Logging date/time in a more readable format, such as
Wed, 10 Nov 2021, 19:26:28 GMT+8. Don't forget to include the timezone if your teams are working in different timezones.
If the script has disruptive consequences, provide a
--dry-runoption to allow others to preview the side effects.
package.jsonis only supposed to be used for running locally on the developers' machine. For running the scripts on the CI, use
npx ts-node scripts/*.tsinstead.
Tips for creating Node.js CLI scripts
24 Nov, 2021Node.js