跨平台 NPM 启动脚本 [英] Cross platform NPM start script

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

问题描述

我正在构建一个 Electron 应用程序,该应用程序将由 Windows 和 OS X 上的人们开发.我想创建一个跨平台的启动脚本.到目前为止,我得到有效的东西的运气完全为零.我认为问题在于我需要设置 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) :

这不是 npm 的工作.如果您愿意,可以运行自定义节点脚本以使用 process.env 设置环境变量,或者使用非环境变量(如 JSON).

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).

...

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

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

(参考:本期)

所以我们将通过一个 JS 脚本进行管理(解决方案灵感来自这个 commit) :

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

  1. scripts目录下创建exec.js文件

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. 更新你的 package.json :

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

  1. 运行 npm 脚本:npm run start

编辑 05.04.2016

有一个非常有用的 npm 包可以解决这个问题:cross-env.跨平台运行设置环境变量的命令

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆