Blake Plumb
Blake Plumb

Reputation: 7199

How to use negation in npm script glob pattern?

I am trying to create a clean npm script but I continue to either get an error in the console or the desired effect does not happen. I am trying to delete all of the root JavaScript files except some config files.

The following removes all of the files ignoring the negate syntax

"clean": "rm -rf lib [a-z].js !*.config.js !*.support.js"

The following throws an error in the console

"clean": "rm -rf lib !(*.config|*.support).js"
Syntax error: "(" unexpected

Upvotes: 3

Views: 2644

Answers (1)

RobC
RobC

Reputation: 24982

Utilize rimraf and wrap the complex glob pattern(s) in JSON escaped double quotes, i.e. \"...\"

For instance:

"clean": "rimraf lib \"!(*.config|*.support).js\""

This example (above)

  1. Deletes the lib directory from the root of the project directory.
  2. Deletes all .js files from the root of the project directory. However, files ending .config.js or .support.js (such as foobar.config.js and quux.support.js) will be negated.

Edit: Using the following bash find command via a npm script also achieves the desired result:

"clean": "find . \\( -name '*.js' -o -name 'lib' \\) -not \\( -name '*.config.js' -o -name '*.support.js' \\) -maxdepth 1 -exec rm -rf {} \\;"

However I'd opt for the aforementioned rimraf approach for greater portability across platforms, including Windows cmd.exe

Upvotes: 4

Related Questions