dylang/npm-check

Detect package usage in npm scripts

Open

#129 建立於 2016年4月8日

在 GitHub 查看
 (1 留言) (2 反應) (0 負責人)JavaScript (6,438 star) (278 fork)batch import
help wantedissue is in a dependency

描述

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"]

貢獻者指南