how to run npm based on os

Viewed 501

i have those 2 npm(s) for each operating system:

"pack": "cd dist/fold1 && type script11.js script22.js script33.js > all.js",
"pack-unix": "cd dist/fold1 && cat script11.js script22.js script33.js > all.js"

how can i make them a single command?

like: "pack": "cd dist/fold1 && <if win than type else cat> script11.js script22.js script33.js > all.js",

4 Answers

There is a great package for this case called run-script-os link here

Note! You can combine OS tags that have similar scripts.

{
  ...
  "scripts": {
    ...
    "pack": "run-script-os",
    "pack:win32": "...",
    "pack:macos": "...",
    "pack:default": "..."
    ...
  },
  ...
}

You can use shelljs/shx as a development only dependency.

npm install shx --save-dev

Then in package.json:

pack: "cd dist/fold1 && shx cat script11.js script22.js script33.js > all.js"

Using shx over run-script-os has an advantage that you don't need to write different scripts for different environments. Prefer using shelljs instead if you are having some complex stuff going on. If your use case(s) are not met by both of them (like a dependency on some specific feature that is not supported by ShellJS), then you can use run-script-os as the other answer suggests, or you can do this: https://stackoverflow.com/a/41551958, if you don't want another dependency.

shx doesn't support running arbitrary commands, and setting environment variables. There is another popular alternative for it: cross-env.

cross-os Good npm package for npm scripts

It supports the following os versions. 'aix' 'darwin' 'freebsd' 'linux' 'openbsd' 'sunos' 'win32'

"scripts": {
  "foo": "cross-os pack",
  "bar": {
    "darwin": "cd dist/fold1 && type script11.js script22.js script33.js > all.js",
    "linux": "cd dist/fold1 && cat script11.js script22.js script33.js > all.js"
  }
}

There's an NPM package called run-script-os ( NPM | GitHub ) that doesn't require you to write any additional files.

And shx: Good for writing one-off commands in npm package scripts (e.g. "clean": "shx rm -rf out/").

npm install shx --save-dev

Reference: https://www.npmjs.com/package/shx#install

Where in package.json: pack: "cd dist/fold1 && shx cat script11.js script22.js script33.js > all.js"

  • ShellJS: Good for writing long scripts, all in JS, running via NodeJS (e.g. node myScript.js).
  • shx is a wrapper around ShellJS Unix commands, providing an easy solution for simple Unix-like, cross-platform commands in npm package scripts.

shx is proudly tested on every node release since v6

Related