Friday, April 20, 2018

yarn binaries, yarn +scripts

$ mkdir test-yarn-run && cd test-yarn-run && yarn init && yarn add jest

Yarn has a nice shortcut to run binaries in node_modules/.bin. Instead of running this:

$ ./node_modules/.bin/jest --help

Or this:

$ $(npm bin)/jest --help

Run this instead:

$ yarn jest --help

However, there's a potential ambiguity that may lead to node_modules' binaries instead of the package.json's scripts be ran with that yarn shortcut, and vice versa.

"test": "yarn jest --config jest.json",
"build": "yarn && yarn jest && yarn webpack -p"

See the potential mistake above? There's a typo on build script, instead of it running the package.json's test script, it run the jest binary in node_modules instead.

With that said, it's a good idea to have a convention that can disambiguate the package.json's scripts from the node_modules' binaries.

One good way to disambiguate them is to prefix the package.json's script with plus sign. It gives a notion that package.json's scripts are additional executables aside from the node_modules' executables.

"+test": "yarn jest --config jest.json",
"+build": "yarn && yarn +jest && yarn webpack -p"

With prefix, the command yarn +jest will immediately flag that +jest command as non-existent, as there are no binaries prefixed with plus on their name.

The plus prefix has a nicer readability for pre and post scripts too. Whereas without the prefix, pre and post scripts are harder to identify if they are part of other script:
"pretest": "yarn lint",
"prebuild": "yarn clean",
"postbuild": "yarn rimraf temp",
"test": "yarn jest --config jest.json",
"build": "yarn && yarn test && webpack -p"

With the prefix, it's immediately obvious that pre+build and post+build are related to +build, likewise with pre+test to +test.

"pre+test": "yarn +lint",
"pre+build": "yarn +clean",
"post+build": "yarn rimraf temp",
"+test": "yarn jest --config jest.json",
"+build": "yarn && yarn +test && webpack -p"

With prefx, it's easy to spot that yarn somethingHere is running a binary, instead of it running a script from the package.json. Saves the hassle of scanning the package.json to see if somethingHere is part of package.json's scripts or not.

Happy Coding!

No comments:

Post a Comment