如何安裝 just 命令執行器:撰寫 justfile、執行 recipe 與 make 對比
安裝 just,寫 justfile 跑 recipe,並知道何時優於 Makefile。
儲存庫里总有「先 lint 再 test 再 build」这类重复命令,写在 README 里没人看,塞进 package.json 的 scripts 又和语言绑定。just 是 Casey Rodarmor 写的命令執行器:在项目根放一个 justfile,用 just 跑具名 recipe,语法比 Make 友好、跨平台也更省心。本教學涵蓋 macOS/Linux 安裝 just、撰寫 justfile、執行 recipe,以及與 make 的對照,面向 hereink 讀者常用的多儲存庫終端工作流。
檢索詞是如何安裝 just 命令執行器並寫 justfile 執行 recipe 對比 make。讀完應能安裝 just、写第一条 recipe、用 just --list 查看任务,并理解何时用 just 替代 Makefile。
just 解决什么问题
可发现的项目命令
新同事不用翻五个文档:just --list 列出所有 recipe 和注释。比「复制粘贴 Slack 里的 curl」更稳。
比 shell 脚本更轻
recipe 默认在项目根执行,可设变量、依赖其他 recipe、传参。不必为每个任务写 ./scripts/foo.sh 并记得 chmod +x。
上游:
github.com/casey/just,文档just.systems。安裝后執行just --version确认。
安裝 just
- 1macOS(Homebrew)
brew install just。验证:which just与just --version。 - 2Linux(发行版包)
Arch:
sudo pacman -S just。Debian/Ubuntu 若儲存庫较旧,可用cargo install just或官方预编译包(见 just.systems 安裝页)。 - 3Rust 工具链
已装 Rust:
cargo install just。确保~/.cargo/bin在PATH里。 - 4版本管理器
mise use -g just@latest或asdf plugin add just(若团队已用 asdf/mise)。
撰寫 justfile
在项目根创建 justfile(或 .justfile)。最小示例:
# 默认 recipe:只输入 just 时執行
default:
just --list
# 带注释,会出现在 just --list
# 跑单元测试
test:
cargo test
# 依赖其他 recipe
check: lint test
echo "all green"
lint:
cargo clippy -- -D warnings常用语法要点:
- recipe 名:
name:下一行起缩进命令(空格,不是 tab)。 - 参数:
deploy env:然后命令里用{{env}}。 - 变量:文件顶部
port := "3000",recipe 内{{port}}。 - shebang recipe:以
#!/usr/bin/env bash开头可写多行 shell。
port := "8080"
# 启动本地服务
serve:
python -m http.server {{port}}
# 带默认值的可选参数
greet name="world":
echo "hello {{name}}"執行 recipe
cd ~/projects/my-app
just --list # 列出 recipe
just test # 執行 test recipe
just check # 先 lint 再 test(依赖顺序)
just greet Alice # 传参
just # 若定义了 default recipejust 会在包含 justfile 的目录(或父目录)查找文件;也可用 just --justfile path/to/justfile recipe。加 -n / --dry-run 只打印将要执行的命令,不真正執行。
与 make 对照
| 方面 | just | make |
|---|---|---|
| 主要用途 | 跑项目命令、编排脚本 | 编译依赖图、构建产物 |
| 语法 | recipe + 现代变量 {{var}} | target: prereq + tab 规则 |
| Windows | 官方支持较好(含 PowerShell 等文档) | 常依赖 GNU make / WSL |
| 文件时间戳 | 不默认当构建系统 | 核心:比 mtime 决定是否重建 |
| 学习曲线 | README 级即可上手 | 大型 Makefile 难维护 |
- 適合 just
- 统一
test/lint/dev入口;多语言儲存庫不想绑 npm scripts;想要比 Make 更可读的 task 列表。 - 仍用 make
- C/C++ 增量编译、复杂依赖图、已有成熟 Makefile 且团队熟悉。
just 和 npm scripts / task 重复吗?
Node 项目可以只用 npm scripts;just 適合 polyglot 儲存庫(Go + Python + 生成步骤)或希望命令与包管理器解耦。两者可并存:just recipe 里调用 npm run build。
recipe 里 cd 子目录有效吗?
每条 recipe 默认在 justfile 所在目录启动;recipe 内 cd 只影响该 recipe 后续行。跨目录任务可用 just --working-directory subdir recipe 或 shebang 脚本。
能调用 .env 里的变量吗?
just 可 set dotenv-load(见官方手册)自动加载 .env。敏感值仍建议 direnv 或 CI secret,不要提交明文。
命令對齊後畫一張圖
本地 just dev 跑通后,服务边界仍適合摊在同一张白板上。见 如何建立空間。