Terminal 系列 - 同時運行多個命令

在開發中常需要同時執行多個命令,concurrently 的出現就是爲了滿足此類場景。

背景

作者喜歡使用 npm[1] 實現任務自動化,但同時運行多個命令的常用方法是 npm run watch-js & npm run watch-css。使用 & 很好,卻很難跟蹤不同的輸出。此外,如果一個進程失敗,其他進程仍會繼續運行,你也不會注意到其中的差異。另一種選擇是在單獨的終端中運行所有命令,但每個命令的運行都必須新開一個終端窗口更令人厭煩。

安裝

因其使用 JS 編寫,所以運行需要依賴 Node.js[2] 環境。

# 全局安裝
npm i -g concurrently

# 項目中安裝(-D: 開發依賴)
npm i -D concurrently

使用

命令使用幫助,以下列舉了部分使用參數,查看文檔瞭解更多 concurrently[3]:

concurrently -h
concurrently 'echo "hello\n"' 'echo "world\n"' "git status"

--raw (-r)

直接輸出子進程:stdout + stderr:

concurrently --raw 'echo "hello\n"' 'echo "world\n"' "git status"

--prefix (-p)

自定義前綴,日期格式請參考 date-fns[4]:

concurrently --prefix "{time}-{pid}" 'echo "hello\n"' 'echo "world\n"' "git status"

--prefix-colors (-c)

自定義前綴顏色,顏色列表請參考 chalk[5]:

concurrently -c "bgBlue.bold,bgMagenta.bold" 'echo "hello\n"' 'echo "world\n"' "git status"

自動改變前綴顏色:

concurrently -c auto --prefix "{time}-{pid}" 'echo "hello\n"' 'echo "world\n"' "git status"

--names

自定義前綴名稱

concurrently --names "HELLO,WORLD,GH" -c "auto" 'echo "hello\n"' 'echo "world\n"' "git status"

名詞解釋

References

[1]

npm: https://www.npmjs.com/

[2]

Node.js: https://nodejs.org/

[3]

concurrently: https://github.com/open-cli-tools/concurrently

[4]

date-fns: https://date-fns.org/v2.0.1/docs/format

[5]

chalk: https://github.com/chalk/chalk

[6]

標準流 (Standard streams): https://en.wikipedia.org/wiki/Standard_streams

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/4Sz30vTvVB8ticfH02SHHg