npm-run-all
提供了自己的自定义机制,通过利用 npm-scripts 中的占位符来处理参数,如参数占位符找到其文档部分here https://github.com/mysticatea/npm-run-all/blob/HEAD/docs/npm-run-all.md#argument-placeholders.
npm 脚本:
鉴于您当前的 npm 脚本名为start
您需要按如下方式重新定义它:
"scripts": {
...
"start": "npm-run-all clean \"build -- {@}\" --parallel watch:build --"
...
}
Notes:
-
-- {@}
must be added after build
.1
-
build -- {@}
必须用转义双引号引起来\"...\"
-
--
还必须在最后一次脚本调用之后添加,即:watch:build
gulpfile.js
要获取通过 CLI 内部传递的参数gulpfile.js你需要利用节点process.argv https://nodejs.org/docs/latest/api/process.html#process_process_argv
为了演示的目的,让我们说我们的gulpfile.js如下:
var gulp = require('gulp');
var args = process.argv.splice(3, process.argv.length - 3);
gulp.task('doSomething', function() {
// For testing purposes...
if (args.indexOf('--foo') > -1) {
console.log('--foo was passed via the CLI.')
}
if (args.indexOf('--quux') > -1) {
console.log('--quux was passed via the CLI.')
}
});
Notes:
-
节点中的前三项process.argv
are:
- 运行 JavaScript 文件的可执行文件的路径。
- 正在执行的 JavaScript 文件的路径。
- gulp 任务的名称,即
doSomething
-
但是,我们只对数组中第四项以后的元素感兴趣 - 因为这些将是通过 CLI 传递的参数。这行内容如下:
var args = process.argv.splice(3, process.argv.length - 3);
创建一个args
变量并分配一个包含通过 CLI 传递的每个参数的数组,即我们使用数组省略了上面第 1 点中提到的前三个项目splice() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice method.
运行你的start
script:
您可以通过 CLI 调用启动脚本,如下所示:
$ npm start -- --foo --quux
Note您必须提供--
其先于npm start
在提供你自己的论点之前。
Output:
Footnotes:
1 -- {@}
can be replaced with -- {1}
if you only intend to pass one argument. However, -- {@}
handles multiple arguments, so it's fine to use it for one argument too.