Prepublish

Along with arbitrary commands and the special test field, the scripts section of the package.json file supports hooks.

The prepublish field can be useful for catching mistakes before we send our code out into the world.

npm scripts
Refer to https://docs.npmjs.com/misc/scripts for a list of all the supported npm scripts.

Let's add a prepublish script that runs npm ls and npm test:

"scripts": {
"prepublish": "npm ls && npm test",
"test": "npm run lint && tap --cov test",
"lint": "standard"
},

Now, npm should check for extraneous dependencies, run our linter, and run our test suite automatically before each publish.

Let's test it real quick by adding an extraneous dependency, as in the preceding section.

This time, our extraneous dependency can be clockface:

npm install clockface 

If we're using npm 5 or greater with default settings, we'll now need to edit our package.json and remove clockface from the dependencies object. This is because in npm 5, dependencies are saved by default so we have to explicitly remove it from the package.json to make it extraneous.

Okay, now we'll bump the patch version:

npm version patch 

Then, we'll try to publish:

npm publish 

At this point, npm should fail to publish and write a npm-debug.log to our modules folder.

When npm ls fails, it exits with a non-zero exit code. The npm task will respect this exit code and similarly fail. A similar situation would occur if one of our tests were failing, or if our code contained syntax that broke linting rules.

Finally, let's fix our mistake and publish for real:

In this case, we don't need clockface, so we'll simply remove it:

rm -fr node_modules/clockface 

Then, we'll publish:

npm publish 

Now, we should see a successful npm ls command, and we should see linting and tests passing, followed by a successful publish of the next version of our module.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.17.40