将命令行参数发送到npm脚本 [英] Sending command line arguments to npm script

查看:175
本文介绍了将命令行参数发送到npm脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 package.json 脚本部分目前如下所示:

The scripts portion of my package.json currently looks like this:

"scripts": {
    "start": "node ./script.js server"
}

...这意味着我可以运行 npm start 启动服务器。到目前为止一直很好。

...which means I can run npm start to start the server. So far so good.

但是,我希望能够运行像 npm start 8080 这样的东西传递给 script.js 的参数(例如 npm start 8080 => 节点./script.js服务器8080 )。这可能吗?

However, I would like to be able to run something like npm start 8080 and have the argument(s) passed to script.js (e.g. npm start 8080 => node ./script.js server 8080). Is this possible?

推荐答案

编辑2014.10.30: 从npm 2.0.0开始,可以将args传递给 npm run

语法如下:

npm run< command> [ - < args>]

请注意必要的 - 。需要将传递给 npm 命令本身的params和传递给你脚本的params分开。

Note the necessary --. It is needed to separate the params passed to npm command itself and params passed to your script.

所以如果你在 package.json

"scripts": {
    "grunt": "grunt",
    "server": "node server.js"
}

然后以下命令是等价的:

Then the following commands would be equivalent:

grunt task:target => npm run grunt - task:target

node server.js --port = 1337 => npm run server - --port = 1337

要获得参数值,查看此问题。要读取命名参数,最好使用像 yargs minimist ; nodejs在全局公开 process.argv ,包含命令行参数值,但这是一个低级API(由空格分隔的字符串数组,由操作系统提供给节点可执行)。

To get the parameter value, see this question. For reading named parameters, it's probably best to use a parsing library like yargs or minimist; nodejs exposes process.argv globally, containing command line parameter values, but this is a low-level API (whitespace-separated array of strings, as provided by the operating system to the node executable).

编辑2013.10.03:目前无法直接使用。但是有一个相关的 GitHub问题在 npm 实现您要求的行为。似乎已达成共识是为了实现这一点,但这取决于之前解决的另一个问题。

Edit 2013.10.03: It's not currently possible directly. But there's a related GitHub issue opened on npm to implement the behavior you're asking for. Seems the consensus is to have this implemented, but it depends on another issue being solved before.

原始答案:作为某种解决方法(虽然不是很方便),您可以执行以下操作:

Original answer: As a some kind of workaround (though not very handy), you can do as follows:

从<$说出您的包裹名称c $ c> package.json 是 myPackage 而你还

"scripts": {
    "start": "node ./script.js server"
}

然后加入 package.json

"config": {
    "myPort": "8080"
}

并且在 script.js 中:

// defaulting to 8080 in case if script invoked not via "npm run-script" but directly
var port = process.env.npm_package_config_myPort || 8080

这样,默认情况下 npm start 将使用8080.您可以配置它(该值将由 npm 存储在其内部存储中):

That way, by default npm start will use 8080. You can however configure it (the value will be stored by npm in its internal storage):

npm config set myPackage:myPort 9090

然后,在调用时 npm start ,将使用9090(默认来自 package.json 被覆盖)。

Then, when invoking npm start, 9090 will be used (the default from package.json gets overridden).

这篇关于将命令行参数发送到npm脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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