Node Cookbook(Third Edition)
上QQ阅读APP看书,第一时间看更新

Extraneous dependencies

It can be all too easy to publish modules without the necessary dependencies.

Let's say that we install the debug module because we want to instrument our code with debug messages.

In the hsl-to-hex folder, we can run this:

npm install debug 
Debugging
The purpose of this section is to demonstrate extraneous dependencies. The fact that we're using the debug module is peripheral; however, we will go into the details of debugging in, Debugging Systems.

Now, let's use debug in our index.js file.

At the top of the file, we can create a debug logger:

var toRgb = require('hsl-to-rgb-for-reals')
var debug = require('debug')('hsl-to-hex')

Now, let's add some debug output in each of our functions.

For the max function, we'll add the following:

function max (val, n) {
debug('ensuring ' + val + 'is no more than ' + n)
/*...snip..*/

It's likewise for the min function:

function min (val, n) {
debug('ensuring ' + val + 'is no less than ' + n)
/*...snip..*/

Finally, this is for the cycle function:

function cycle (val) {
debug('resolving ' + val + ' within the 0-359 range')
/*...snip..*/

Okay, it looks good.

Let's run our tests to ensure that everything is working:

npm test 

We can also check whether our debug logs work by running this:

DEBUG=hsl-to-hex node example.js 

If all goes well, we can be fooled into believing that we are ready to publish a new version of our module. However, if we do, it will be broken on arrival.

This is because we neglected to add the debug module to the package.json file. We omitted the --save flag.

The tests and code work for us because the debug module is installed, but npm does not know to install it for the users of our module because we haven't told npm to do so.

A good habit to get into is running npm ls before publishing, as follows:

npm ls 

This will output a dependency tree for all our production and development modules. More importantly, it also identifies extraneous dependencies, that is, dependencies that are in the node_modules folder but aren't specified in the package.json file.

In our case, the bottom of the npm ls output will say this:

npm ERR! extraneous: debug@2.2.0 /Users/davidclements/z/Node-Cookbook-3rd-Ed/1-Writing-Modules/source/publishing-a-module/listing-installed-modules/hsl-to-hex/node_modules/debug 

To fix the extraneous dependency, we can manually edit the package.json file dependencies field, or we can simply run the install command again with the --save flag, as demonstrated:

npm install --save debug