Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 418
Miroslav Válka - MWarCZ Avatar asked Aug 09 '18 13:08

Miroslav Válka - MWarCZ


1 Answers

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"
  }
}
like image 60
Miroslav Válka - MWarCZ Avatar answered Nov 15 '22 22:11

Miroslav Válka - MWarCZ