npm glob pattern not matching subdirectories

后端 未结 3 576
面向向阳花
面向向阳花 2020-12-17 09:48

In my package.json, I have a scripts block that uses **/*Test.js to match files. When run via npm, they do not match sub-directories m

3条回答
  •  醉梦人生
    2020-12-17 10:06

    Solution

    Change your scripts so that what you pass to Mocha is protected from expansion by the shell:

    "scripts": {
        "test": "mocha 'dist/**/*Test.js'",
     }
    

    Note the single quotes around the parameter given to mocha.

    Explanation

    This issue is fixable without resorting to external tools. The root cause of your problem is that by npm uses sh as the shell that will run your script commands.

    It is overwhelmingly the case that when a *nix process starts a shell it will start sh unless there is something telling it to do otherwise. The shell preference you set for logins does not constitute a way to "tell it otherwise". So if you have, say, zsh as your login shell, it does not entail that npm will use zsh.

    Those implementations of sh that do not include any extensions beyond what sh should provide do not understand the ** glob in the way you want it to. As far as I can tell, it is interpreted as *. However, Mocha interprets the paths passed to it using its a JavaScript implementation of globs. So you can work around the issue by protecting your globs from being interpreted by sh. Consider the following package.json:

    {
      "name": "immutable-ts",
      "scripts": {
        "bad": "mocha test/**/*a.js",
        "good": "mocha 'test/**/*a.js'",
        "shell": "echo $0"
      }
    }
    

    The shell script is just so that we can check what shell is running the script. If you run it, you should see sh.

    Now, given the following tree:

    test/
    ├── a.js
    ├── b.js
    ├── x
    │   ├── a
    │   │   ├── a.js
    │   │   └── b.js
    │   ├── a.js
    │   └── b
    │       └── a.js
    └── y
        ├── a.js
        └── q
    

    With all a.js and b.js files containing it(__filename);. You get the following results:

    $ npm run bad
    
    > immutable-ts@ bad /tmp/t2
    > mocha test/**/*a.js
    
      - /tmp/t2/test/x/a.js
      - /tmp/t2/test/y/a.js
    
      0 passing (6ms)
      2 pending
    
    $ npm run good
    
    > immutable-ts@ good /tmp/t2
    > mocha 'test/**/*a.js'
    
      - /tmp/t2/test/a.js
      - /tmp/t2/test/x/a.js
      - /tmp/t2/test/x/a/a.js
      - /tmp/t2/test/x/b/a.js
      - /tmp/t2/test/y/a.js
    
      0 passing (5ms)
      5 pending
    

提交回复
热议问题