简体   繁体   中英

How to detect that the script is running with npm or yarn?

I need to write universal scripts for npm and yarn.

package.json for npm:

{
  "scripts": {
    "build:clean": "rim-raf dist",
    "test:clean": "rim-raf coverage",
    "clean": "npm run build:clean; npm run test:clean"
  }
}

package.json for yarn:

{
  "scripts": {
    "build:clean": "rim-raf dist",
    "test:clean": "rim-raf coverage",
    "clean": "yarn run build:clean; yarn run test:clean"
  }
}

package.json for npm and yarn:

I usually use little hack: $_

{
  "scripts": {
    "build:clean": "rim-raf dist",
    "test:clean": "rim-raf coverage",
    "clean": "$_ run build:clean; $_ run test:clean"
  }
}

But sometime it does not work correctly.

Exists some legit way to do this?

Edit:

I found solution I was looking for.

SOLVED

I think I found the optimal solution.

I searched in npm env and compared it with yarn env . I found the variable $npm_execpath that contains the path to used package manager. (For Windows %npm_execpath% )

package.json for npm and yarn:

{
  "scripts": {
    "build:clean": "rim-raf dist",
    "test:clean": "rim-raf coverage",
    "clean": "$npm_execpath run build:clean; $npm_execpath run test:clean"
  }
}

My final solution package.json for npm and yarn works on Linux, Windows, Mac:

If add package cross-var , scripts works on Linux, Windows and Mac.

{
  "scripts": {
    "build:clean": "rim-raf dist",
    "test:clean": "rim-raf coverage",
    "clean": "cross-var $npm_execpath run build:clean; cross-var $npm_execpath run test:clean"
  }
}

You could try this 3rd party module:

https://github.com/BendingBender/yarpm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM