本文介绍了跨平台NPM启动脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个由Windows和OS X上的人们开发的Electron应用程序。我想创建一个跨平台的启动脚本。到目前为止,我的运气完全为零。我认为,问题是我需要设置 NODE_ENV 环境变量,并且语法略有不同。

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?

推荐答案

环境变量在Windows中是个问题。

Environment variables are a problem in Windows.

如上所述Domenic Denicola(npm的主要贡献者之一):

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

...

您可以编写自定义脚本来解决connect的限制,例如在您的测试中修改process.env。

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

(参考:)

因此,我们将通过JS脚本进行管理(解决方案的灵感来自):

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


  1. 创建一个<$ 脚本目录中的c $ c> exec.js 文件

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

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. 更新您的软件包.json

  1. Update your package.json :


"scripts": {
    "start": "node scripts/exec.js development",
}




  1. 运行npm脚本: npm运行开始

  1. Run npm script : npm run start

编辑05.04.2016

有一个非常有用的npm软件包,可以解决此问题:。运行跨平台设置环境变量的命令

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

这篇关于跨平台NPM启动脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 17:48