Press "Enter" to skip to content

使用 asdf 在 macOS(Apple Silicon)上管理 Golang 与 Node.js

内容目录

适用人群:

  • 使用 Apple Silicon
  • 需要管理 多个 Go / Node 版本
  • 希望做到 全局 + 项目级版本可切换

一、为什么选择 asdf

asdf 是一个多语言版本管理器,相比 brew 或单语言工具:

  • ✅ 一个工具管理 Go / Node / Python / Java…
  • ✅ 支持 项目级版本锁定.tool-versions
  • ✅ 适合团队协作和 CI
  • ✅ 对 Apple Silicon 友好,避免架构混乱

结论:

  • 系统工具 → brew
  • 语言运行时 → asdf

二、安装 asdf(0.18+)

1️⃣ 使用 Homebrew 安装

brew install asdf

2️⃣ 初始化 asdf(必须)

~/.zshrc 中加入:

. "$(brew --prefix asdf)/libexec/asdf.sh"

然后:

source ~/.zshrc

验证:

asdf --version

三、使用 asdf 安装 Golang

1️⃣ 添加 Go 插件

asdf plugin add golang

2️⃣ 查看可用 Go 版本

asdf list all golang

会列出从历史版本到最新版本的所有 Go。

3️⃣ 安装指定 Go 版本

asdf install golang 1.22.7

4️⃣ 设置 Go 版本(asdf 0.18+ 新方式)

全局 Go(写入 ~/.tool-versions

cd ~
asdf set golang 1.22.7

项目级 Go(推荐)

cd your-go-project
asdf set golang 1.21.6

会生成:

.tool-versions
golang 1.21.6

5️⃣ 验证

which go
go version

期望结果:

~/.asdf/shims/go
go version go1.22.7 darwin/arm64

四、使用 asdf 安装 Node.js

1️⃣ 添加 Node 插件

asdf plugin add nodejs

(如遇到 key 校验问题,可执行)

asdf nodejs update-nodebuild

2️⃣ 查看可用 Node 版本

asdf list all nodejs

3️⃣ 安装 Node(推荐 LTS)

asdf install nodejs lts

或指定版本:

asdf install nodejs 20.11.1

4️⃣ 设置 Node 版本

全局 Node

cd ~
asdf set nodejs 20.11.1

项目级 Node(强烈推荐)

cd your-node-project
asdf set nodejs 18.19.0

5️⃣ 验证

which node
node -v

期望结果:

~/.asdf/shims/node
v20.11.1

五、全局 vs 项目级版本说明(重点)

asdf 的版本解析优先级(从高到低)

  1. 当前目录 .tool-versions
  2. 父目录 .tool-versions
  3. 家目录 ~/.tool-versions(全局)
  4. 系统 PATH

推荐实践

  • ~/.tool-versions
    → 放最新、最常用版本(兜底)
  • 每个项目目录
    → 放项目实际需要的版本

示例:

# ~/.tool-versions
golang 1.22.7
nodejs 20.11.1
# project/.tool-versions
golang 1.21.6
nodejs 18.19.0

进入目录自动切换,无需手动操作。


六、Node 包管理(npm / pnpm / yarn)

npm

  • Node 自带
  • 无需额外安装

七、升级 / 卸载版本

升级 Go 或 Node

asdf install golang 1.23.1
asdf set golang 1.23.1
asdf install nodejs 22.2.0
asdf set nodejs 22.2.0

卸载旧版本

asdf uninstall golang 1.21.6
asdf uninstall nodejs 18.19.0

八、常见问题与避坑

1️⃣ 不要混用 brew 安装语言运行时

brew install go
brew install node

否则会导致 PATH 冲突。

2️⃣ 排查版本不生效

which go
asdf which go
asdf current

3️⃣ Go Modules 说明(简要)

  • 依赖缓存:GOMODCACHE
  • 不会装进项目目录
  • asdf 下 每个 Go 版本有独立 module cache

九、总结

  • ✅ asdf 是多语言版本管理的最佳实践之一
  • ✅ Go / Node 强烈建议用 asdf 管理
  • ✅ 项目级 .tool-versions 是核心价值
  • ❌ 不要与 brew 的语言版本混用

一旦习惯:
cd 目录 = 自动切版本

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注