Javascript 将命令行参数发送到 npm 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11580961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:23:32  来源:igfitidea点击:

Sending command line arguments to npm script

javascriptnode.jsnpm

提问by arnemart

The scriptsportion of my package.jsoncurrently looks like this:

scriptspackage.json目前的部分看起来像这样:

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

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

...这意味着我可以运行npm start以启动服务器。到现在为止还挺好。

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

但是,我希望能够运行类似的东西npm start 8080并将参数传递给script.js(例如npm start 8080=> node ./script.js server 8080)。这可能吗?

回答by jakub.g

Edit 2014.10.30:It's possible to pass args to npm runas of npm 2.0.0

编辑 2014.10.30:可以将 args 传递给npm runnpm 2.0.0

The syntax is as follows:

语法如下:

npm run <command> [-- <args>]

npm run <command> [-- <args>]

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

注意必要的--. 需要将传递给npm命令本身的参数和传递给脚本的参数分开。

So if you have in package.json

所以如果你有 package.json

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

Then the following commands would be equivalent:

那么以下命令将是等效的:

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

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

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

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

To get the parameter value, see this question. For reading named parameters, it's probably best to use a parsing library like yargsor minimist; nodejs exposes process.argvglobally, 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).

要获取参数值,请参阅此问题。为了读取命名参数,最好使用像yargsminimist这样的解析库;nodejsprocess.argv全局公开,包含命令行参数值,但这是一个低级 API(以空格分隔的字符串数组,由操作系统提供给节点可执行文件)。



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

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



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

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

Say your package name from package.jsonis myPackageand you have also

说你的包名来自package.jsonmyPackage,你也有

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

Then add in package.json:

然后加入package.json

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

And in your script.js:

而在你的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

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

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

npm config set myPackage:myPort 9090

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

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

回答by cjerdonek

You asked to be able to run something likenpm start 8080. This is possible without needing to modify script.jsor configuration files as follows.

您要求能够运行类似npm start 8080. 这是可能的,无需修改script.js或配置文件,如下所示。

For example, in your "scripts"JSON value, include--

例如,在您的"scripts"JSON 值中,包括--

"start": "node ./script.js server $PORT"

And then from the command-line:

然后从命令行:

$ PORT=8080 npm start

I have confirmed that this works using bash and npm 1.4.23. Note that this work-around does not require GitHub npm issue #3494to be resolved.

我已经确认这使用 bash 和 npm 1.4.23 有效。请注意,此变通方法不需要解决 GitHub npm问题 #3494

回答by francoisrv

You could also do that:

你也可以这样做:

In package.json:

package.json

"scripts": {
    "cool": "./cool.js"
}

In cool.js:

cool.js

 console.log({ myVar: process.env.npm_config_myVar });

In CLI:

在 CLI 中:

npm --myVar=something run-script cool

Should output:

应该输出:

{ myVar: 'something' }

Update: Using npm 3.10.3, it appears that it lowercases the process.env.npm_config_variables? I'm also using better-npm-run, so I'm not sure if this is vanilla default behavior or not, but this answer isworking. Instead of process.env.npm_config_myVar, try process.env.npm_config_myvar

更新:使用 npm 3.10.3,它似乎将process.env.npm_config_变量小写?我也在使用better-npm-run,所以我不确定这是否是普通的默认行为,但这个答案有效的。而不是process.env.npm_config_myVar,尝试process.env.npm_config_myvar

回答by svnm

jakub.g's answer is correct, however an example using grunt seems a bit complex.

jakub.g的答案是正确的,但是使用 grunt 的示例似乎有点复杂。

So my simpler answer:

所以我更简单的答案:

- Sending a command line argument to an npm script

- 向 npm 脚本发送命令行参数

Syntax for sending command line arguments to an npm script:

将命令行参数发送到 npm 脚本的语法:

npm run [command] [-- <args>]

Imagine we have an npm start task in our package.json to kick off webpack dev server:

想象一下,我们在 package.json 中有一个 npm start 任务来启动 webpack 开发服务器:

"scripts": {
  "start": "webpack-dev-server --port 5000"
},

We run this from the command line with npm start

我们从命令行运行它 npm start

Now if we want to pass in a port to the npm script:

现在,如果我们想将端口传递给 npm 脚本:

"scripts": {
  "start": "webpack-dev-server --port process.env.port || 8080"
},

running this and passing the port e.g. 5000 via command line would be as follows:

运行它并通过命令行传递端口(例如 5000)将如下所示:

npm start --port:5000

- Using package.json config:

- 使用 package.json 配置:

As mentioned by jakub.g, you can alternatively set params in the config of your package.json

正如jakub.g所提到的,您也可以在package.json的配置中设置参数

"config": {
  "myPort": "5000"
}

"scripts": {
  "start": "webpack-dev-server --port process.env.npm_package_config_myPort || 8080"
},

npm startwill use the port specified in your config, or alternatively you can override it

npm start将使用您的配置中指定的端口,或者您可以覆盖它

npm config set myPackage:myPort 3000

- Setting a param in your npm script

- 在你的 npm 脚本中设置一个参数

An example of reading a variable set in your npm script. In this example NODE_ENV

读取 npm 脚本中设置的变量的示例。在这个例子中NODE_ENV

"scripts": {
  "start:prod": "NODE_ENV=prod node server.js",
  "start:dev": "NODE_ENV=dev node server.js"
},

read NODE_ENV in server.jseither prodor dev

在阅读NODE_ENV server.js无论是督促开发

var env = process.env.NODE_ENV || 'prod'

if(env === 'dev'){
    var app = require("./serverDev.js");
} else {
    var app = require("./serverProd.js");
}

回答by Gregory Houllier

npm 2.x supportcli args

npm 2.x 支持cli 参数

Command

命令

npm run-script start -- --foo=3

npm run-script start -- --foo=3

Package.json

包.json

"start": "node ./index.js"

"start": "node ./index.js"

Index.js

索引.js

console.log('process.argv', process.argv);

console.log('process.argv', process.argv);

回答by Peter

Use process.argvin your code then just provide a trailing $*to your scripts value entry.

process.argv在您的代码中使用,然后只需为$*您的脚本值条目提供一个尾随。

As an example try it with a simple script which just logs the provided arguments to standard out echoargs.js:

举个例子,用一个简单的脚本来尝试它,它只将提供的参数记录到标准输出echoargs.js

console.log('arguments: ' + process.argv.slice(2));

package.json:

包.json:

"scripts": {
    "start": "node echoargs.js $*"
}

Examples:

例子:

> npm start 1 2 3
arguments: 1,2,3

process.argv[0]is the executable (node), process.argv[1]is your script.

process.argv[0]是可执行文件(节点),process.argv[1]是您的脚本。

Tested with npm v5.3.0 and node v8.4.0

使用 npm v5.3.0 和 node v8.4.0 测试

回答by Dan Ross

If you want to pass arguments to the middle of an npm script, as opposed to just having them appended to the end, then inline environment variables seem to work nicely:

如果您想将参数传递到 npm 脚本的中间,而不是将它们附加到末尾,那么内联环境变量似乎可以很好地工作:

"scripts": {
  "dev": "BABEL_ARGS=-w npm run build && cd lib/server && nodemon index.js",
  "start": "npm run build && node lib/server/index.js",
  "build": "mkdir -p lib && babel $BABEL_ARGS -s inline --stage 0 src -d lib",
},

Here, npm run devpasses the -wwatch flag to babel, but npm run startjust runs a regular build once.

在这里,npm run dev-w监视标志传递给 babel,但npm run start只运行一次常规构建。

回答by Andrew Odri

I had been using this one-liner in the past, and after a bit of time away from Node.js had to try and rediscover it recently. Similar to the solution mentioned by @francoisrv, it utilizes the node_config_*variables.

我过去一直在使用这种单线,在离开 Node.js 一段时间后,最近不得不尝试重新发现它。类似于@francoisrv 提到的解决方案,它利用了node_config_*变量。

Create the following minimal package.jsonfile:

创建以下最小package.json文件:

{
  "name": "argument",
  "version": "1.0.0",
  "scripts": {
    "argument": "echo \"The value of --foo is '${npm_config_foo}'\""
  }
}

Run the following command:

运行以下命令:

npm run argument --foo=bar

Observe the following output:

观察以下输出:

The value of --foo is 'bar'

--foo 的值是 'bar'

All of this is nicely documented in the npm official documentation:

所有这些都很好地记录在 npm 官方文档中:

Note:The Environment Variablesheading explains that variables inside scripts do behave differently to what is defined in the documentation. This is true when it comes to case sensitivity, as well whether the argument is defined with a space or equals sign.

注:环境变量标题解释说,里面的脚本变量也表现不同,以什么文档中定义。当涉及到区分大小写以及参数是用空格还是等号定义时,情况确实如此。

Note:If you are using an argument with hyphens, these will be replaced with underscores in the corresponding environment variable. For example, npm run example --foo-bar=bazwould correspond to ${npm_config_foo_bar}.

注意:如果您使用带连字符的参数,这些将在相应的环境变量中替换为下划线。例如,npm run example --foo-bar=baz将对应于${npm_config_foo_bar}

Note:For non-WSL Windows users, see @Doctor Blue's comments below... TL;DR replace ${npm_config_foo}with %npm_config_foo%.

注意:对于非 WSL Windows 用户,请参阅下面@Doctor Blue 的评论... TL;DR 替换${npm_config_foo}%npm_config_foo%.

回答by Alexandr Priezzhev

Most of the answers above cover just passing the arguments into your NodeJS script, called by npm. My solution is for general use.

上面的大多数答案只是将参数传递到由 npm 调用的 NodeJS 脚本中。我的解决方案是通用的。

Just wrap the npm script with a shell interpreter (e.g. sh) call and pass the arguments as usual. The only exception is that the first argument number is 0.

只需使用 shell 解释器(例如sh)调用包装 npm 脚本并像往常一样传递参数。唯一的例外是第一个参数编号是0

For example, you want to add the npm script someprogram --env=<argument_1>, where someprogramjust prints the value of the envargument:

例如,您想添加 npm script someprogram --env=<argument_1>,其中someprogram只打印env参数的值:

package.json

包.json

"scripts": {
  "command": "sh -c 'someprogram --env=
% npm run -s command my-environment
my-environment
'" }

When you run it:

当你运行它时:

"scripts": {
    "start": "PORT=3000 node server.js"
}

回答by DrunkenBeetle

This doesn't really answer your question but you could always use environment variables instead:

这并不能真正回答您的问题,但您始终可以改用环境变量:

var port = process.env.PORT || 3000;

Then in your server.js file:

然后在你的 server.js 文件中:

##代码##