A collection of useful npm scripts tricks
Get the current ("initial") directory that an npm script was run:
// <project root>/package.json
{
"scripts": {
"deck": "mdx-deck $INIT_CWD/index.mdx"
}
}Usage:
packages/presentation-1 $ npm run deck # runs mdx-deck /Users/user/projects/decks/packages/presentation-1/index.mdxBackground / Discussion: npm/npm#9374 (comment)
If you want to use regular expressions with features like backreferences, you may consider using sed within your npm script.
The escaping in the regular expression is a bit weird (probably because of JSON).
This example uses the s@pattern@replace@ syntax to avoid having to escape the folder slashes.
{
"scripts": {
"names": "for file in dir/*.md; do echo `echo $file | sed 's@dir/\\(.*\\)\\.md@\\1.pdf@'`; done"
}
}Usage:
# Files within dir:
# dir/abc.md
# dir/def.md
npm run names
abc.pdf
def.pdfIf a process exits for any reason, restart it, with an optional message.
{
"scripts": {
"develop": "until gatsby develop; do echo "Gatsby crashed with exit code $?. Restarting.." >&2; sleep 1; done"
}
}Usage:
$ npm run developStack Overflow: https://stackoverflow.com/a/697064/1268612
To loop / foreach over all files matching a pattern.
{
"scripts: {
"build": "for file in dir/*.md; do md-to-pdf $file; done"
}
}Usage:
npm run build # will loop over all the .md files in the directory "dir" and run md-to-pdf with eachEver want to use Bash positional parameters / arguments / variables in npm scripts?
Here's two ways:
{
"scripts": {
"1": "f(){ mdx-deck $1 index.mdx; }; f",
"2": "bash -c 'mdx-deck $1 index.mdx' --"
}
}Usage:
npm run 1 # runs mdx-deck index.mdx
npm run 1 build # runs mdx-deck build index.mdx{
"scripts": {
"1": "f(){ mdx-deck $* index.mdx; }; f",
"2": "bash -c 'mdx-deck $* index.mdx' --"
}
}Usage:
npm run 1 build blah another # runs mdx-deck build blah another index.mdxDefault values are achieved by testing values of $1 and whether something is included in $*:
{
"scripts": {
"1": "f(){ mdx-deck $* $([[ $1 = build && ! $* =~ '-d' ]] && echo \"-d default\" || echo \"\") index.mdx; }; f",
"2": "bash -c 'mdx-deck $* $* $([[ $1 = build && ! $* =~ '-d' ]] && echo \"-d default\" || echo \"\") index.mdx' --"
}
}Usage:
npm run 1 build # runs mdx-deck build -d default index.mdx
npm run 1 build -d different # runs mdx-deck build -d different index.mdxTweet 1: https://mobile.twitter.com/karlhorky/status/1136577374072573952
Tweet 2: https://mobile.twitter.com/karlhorky/status/1136584417533730816
Background / Discussion: npm/npm#9627 (comment)