How to create cross-platform scripts (multiple commands for one line) in package.json (nodeJs)

Question: in script: we want to check env. variable {dev / test / mock} and execute the following script actions based on this.

if $ mock is true, run script start-mock else continue accessing the real test server


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

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

scenario 2: there may be a bat / sh script sitting in a package, and we called them from package.json

Scenario 3: (permanent solution) not sure if it is already available there

sort of

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

where we can have a script for processing (input from process.platform) out put depends on the OS.


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

+5
source share
3 answers

Let's look at the implementation of the 3rd solution, for example,

package.json

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

bin / command.js

 var spawn = require('child_process').spawn; var platform = require('os').platform(); var cmd = /^win/.test(platform) ? 'bin\\command.bat' : 'bin/command.sh'; spawn(cmd, [], { stdio: 'inherit' }).on('exit', function(code) { process.exit(code); }); 

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

+3
source

Usage: run-script-os

For instance:

 // 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
source

You will need to implement solution 3.

You can use the cross-env package to do this for you.

+1
source

Source: https://habr.com/ru/post/1262527/


All Articles