dylang/npm-check

Detect package usage in npm scripts

Open

#129 opened on Apr 8, 2016

View on GitHub
 (1 comment) (2 reactions) (0 assignees)JavaScript (6,438 stars) (278 forks)batch import
help wantedissue is in a dependency

Description

At the moment, npm packages that are installed and used in npm scripts are incorrectly marked as unused. It is possible to detect at least some of them, which I think would be an improvement.

e.g.

I'm using the rimraf package in my npm run clean script, which cleans up after generating coverage reports. npm-check outputs the following:

rimraf                                      😟  MISSING!  Not installed.
                                            😕  NOTUSED?  Still using rimraf?

In my package.json I am defining the following in the scripts section:

  "clean": "rimraf ./coverage"

An example of a more complex npm script:

if [ -n \"$CODECLIMATE_REPO_TOKEN\" ]; then codeclimate-test-reporter < coverage/lcov.info; fi

We could use the following to find packages used in npm scripts:

function getPackagesFromScript (str) {
    var exclude = ['node', 'npm', 'if'];
    var matches = [];
    var matcher = /(?:^|(?:\&+\s+)|then\s+)([a-zA-Z][\w\-]*)/g;
    var result;
    while ((result = matcher.exec(str)) !== null) {
        if (exclude.includes(result[1]) || matches.includes(result[1])) continue;
        matches.push(result[1]);
    }
    return matches;
}

This is a quick and dirty function built from my own set of scripts, but it detects the following packages correctly from real world npm scripts:

getPackagesFromScript('eslint .')
> ["eslint"]
getPackagesFromScript('istanbul cover ./node_modules/mocha/bin/_mocha && rimraf ./coverage')
> ["istanbul", "rimraf"]
getPackagesFromScript('npm run lint && npm run test-unit')
> []
getPackagesFromScript('node server.js')
> []
getPackagesFromScript('if [ -n \"$CODECLIMATE_REPO_TOKEN\" ]; then codeclimate-test-reporter < coverage/lcov.info; fi')
> ["codeclimate-test-reporter"]

Contributor guide