npm package.json OS specific script

gawi picture gawi · Jul 13, 2017 · Viewed 13.6k times · Source

I would like to create a package.json build script that executes slightly different set of commands when run from Windows, Linux, Mac.

The problem is that I cannot find a way to put it in package.json file that will run without problems at every system.

Here is an example that I would like to have:

"scripts" : {
    "build.windows" : "echo do windows specific stuff",
    "build.linux" : "echo do linux specific stuff",
    "build.mac" : "echo do mac specific stuff",
    "build" : "??????????????" <- what to put here to execute script designed for OS
                                  on which npm is running
}

Answer

Dave P picture Dave P · Nov 7, 2018

There's an NPM package called run-script-os ( NPM | GitHub ) that doesn't require you to write any additional files, and this can be convenient if what you're trying to do is very simple. For example, in your package.json, you might have something like:

"scripts": {
    "test": "run-script-os",
    "test:darwin:linux": "export NODE_ENV=test && mocha",
    "test:win32": "SET NODE_ENV=test&& mocha"
}

Then you could run npm test on Windows, Mac, or Linux and get similar (or different!) results on each.