要求用户输入 npm 脚本的值

Mar*_*rev 15 npm

我有一个 npm 脚本,其运行方式如下:

npm run start:local -- -target.location https://192.1.1.1:8052/
Run Code Online (Sandbox Code Playgroud)

URL参数是用户的本地IP。

我希望要求用户输入这个值,因为每个人的值都不同。

是否可以?使用 vanila npm 脚本来做到这一点会很棒。

SNi*_*ill 12

简单来说,annpm script将在您的 shell 环境中运行所需的命令。

在 shell 脚本中,可以使用$NN = 参数位置来访问传递的参数。

谈论您的情况,您要运行的命令是 npm run start:local -- -target.location USER_INPUT USER_INPUT 需要替换为用户传递的参数。假设用户将位置作为第一个参数传递给脚本,则可以使用$1.

我创建这个要点是为了证明这一点。

在此输入图像描述

正如您可以清楚地看到的,我已定义start:local访问第一个参数,然后将其传递给start脚本,然后脚本回显传入的参数。

在此输入图像描述

更新: 这是以提示格式向用户询问值的脚本。 在此输入图像描述

基本上,首先我要求用户输入,然后将其存储在变量中并将该变量作为参数传递给npm start

在此输入图像描述

参考


Pro*_*eek 11

使用readline获取ip值然后使用exec生成此进程。这是一个纯 JS 解决方案,与操作系统无关。

例子:

包.json
"scripts": {
    "start": "npm run start:local -- -target.location",
    "prompt": "node prompt.js"
},
Run Code Online (Sandbox Code Playgroud)
提示.js
const { spawn, execSync } = require('child_process');
const exec = commands => {
  execSync(commands, { stdio: 'inherit', shell: true });
};
const spawnProcess = commands => {
  spawn(commands, { stdio: 'inherit', shell: true });
};
   const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

rl.question('What is your current ip? example: https://192.168.1.10:9009 ', (ip) => {
  console.log(`Starting server on: ${ip}`);
  exec(`npm run start -- ${ip}`);
  rl.close();
});
Run Code Online (Sandbox Code Playgroud)