Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cross platform NPM start script

Tags:

npm

electron

I'm building out an Electron app that will be developed by folks on both Windows and OS X. I'd like to create a cross-platform start script. So far, I've had exactly zero luck getting something that works. The issue, I think, is that I need to set the NODE_ENV environment variable and the syntax is slightly different.

I'm hoping there's a way that I just haven't found yet. My current scripts section follows:

"scripts": {
    "start:osx": "NODE_ENV=development electron ./app/",
    "start:win": "set NODE_ENV=development && electron ./app/"
}

I'd really like to create a single "start" script and eliminate the platform-specific variants. Is it possible?

like image 697
Rob Wilkerson Avatar asked Oct 06 '15 13:10

Rob Wilkerson


People also ask

What script does npm start run?

So npm start runs the node script that is listed under start in the package. json.

Can the npm run all CLI tool run multiple npm scripts in parallel?

Moving on, this package is another popular option from NPM, called NPM-Run-All. The NPM page proclaims npm-run-all “A CLI tool to run multiple npm-scripts in parallel or sequential.”


Video Answer


1 Answers

Environment variables are a problem in Windows.

As stated Domenic Denicola (one of the main contributors to npm) :

This is not npm's job. You can run custom Node scripts to set environment variables using process.env if you'd like, or use something that isn't environment variables (like JSON).

...

You can write custom scripts to work around connect's limitations, e.g. in your tests modify process.env.

(Reference : this issue)

So we'll manage through a JS script (Solution inspired on this commit) :

  1. Create a exec.js file in a scripts directory

  2. Copy the following code in exec.js :

var exec = require('child_process').exec;

var command_line = 'electron ./app/';
var environ = (!process.argv[2].indexOf('development')) ? 'development' : 'production';

if(process.platform === 'win32') {
  // tricks : https://github.com/remy/nodemon/issues/184#issuecomment-87378478 (Just don't add the space after the NODE_ENV variable, just straight to &&:)      
  command_line = 'set NODE_ENV=' + environ + '&& ' + command_line;
} else {
  command_line = 'NODE_ENV=' + environ + ' ' + command_line;
}

var command = exec(command_line);

command.stdout.on('data', function(data) {
  process.stdout.write(data);
});
command.stderr.on('data', function(data) {
  process.stderr.write(data);
});
command.on('error', function(err) {
  process.stderr.write(err);
});
  1. Update your package.json :
"scripts": {
    "start": "node scripts/exec.js development",
}
  1. Run npm script : npm run start

Edit 05.04.2016

There is a very useful npm package that allows manages this problem : cross-env. Run commands that set environment variables across platforms

like image 196
forresst Avatar answered Oct 22 '22 19:10

forresst