how to create cross platform scripts (multiple command for single line) in package.json (nodeJs)

若如初见. 提交于 2020-05-23 02:51:09

问题


issue: in script: we want to check env. variable {dev/test/mock} and do following script run based on it.

if $mock is true the run script start-mock else go on reach real test server


scenario 1: we added commands aggregated in package.json script section

e.g. : "test": "export NODE_ENV=dev; grunt", [on linux]
which is "test": "(SET NODE_ENV=dev) & (grunt)", [on win32]

scenario 2: could be bat/sh script sitting in package and we called them out from package.json

scenario 3: (permanent solution) not sure if its already available out there

something like

get arguments from script section: to give flexibility and freedom to end user.
 e.g. : "test": "solution.env NODE_ENV=dev; solution grunt"

where we can have script to process (input with process.platform) out put depends on OS.


"start-pm2": "if \"%MOCK%\" == \"true\" ( npm run mock & pm2 start process.json --env test ) else ( pm2 start process.json )", [windows] for linux if.. fi


回答1:


Use: run-script-os

For example:

// from pacakge.json
"scripts": {
    // ...
    "dist": "run-script-os",
    "dist:win32": "tar -C dist -cvzf %npm_package_name%-%npm_package_version%.tgz .",
    "dist:linux": "tar -C dist -cvzf $npm_package_name-$npm_package_version.tgz ."
},



回答2:


Lets consider implementation of 3-th solution like e.g.

package.json

"scripts": {
  "command" : "node bin/command.js"
}

bin/command.js

const spawn = require("child_process").spawn
const platform = require("os").platform()
const cmd = /^win/.test(platform)
  ? `${process.cwd()}\\bin\\command.bat`
  : `${process.cwd()}/bin/command.sh`

spawn(cmd, [], { stdio: "inherit" }).on("exit", code => process.exit(code))

depends on environments script will execute command.bat or command.sh




回答3:


You will need to implement solution 3.

You can use cross-env package that does it for you.



来源:https://stackoverflow.com/questions/41548990/how-to-create-cross-platform-scripts-multiple-command-for-single-line-in-packa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!