自动同步 .env 文件到 GitHub Actions
提示
NEXTY.DEV v3.2.16 新增两个生产环境变量同步脚本,如果你本地代码没有以下两个脚本,请到源码仓库下载:
sync-env-to-github.mjs:将本地.env文件中的环境变量批量创建到 GitHub Actions 的 Secrets 和 Variables 中clear-env-form-github.mjs:清空 GitHub Actions 的 Secrets 和 Variables 中的环境变量
本指南教你如何使用脚本自动将本地 .env 文件中的环境变量批量创建到 GitHub Actions 的 Secrets 和 Variables 中。
前置准备
- 安装 GitHub CLI
MacOS 安装方法:
brew install ghWindows 安装方法:
winget install --id GitHub.cli
或
scoop install gh- 登录 GitHub
gh auth login按照交互式提示完成登录。
- 确保仓库权限
你需要对目标仓库拥有 Admin 权限才能创建 Secrets 和 Variables。
脚本使用
在 package.json 文件中,找到 scripts 配置,添加以下命令:
"scripts": {
"env:clear": "node scripts/clear-env-from-github.mjs",
"env:sync": "node scripts/sync-env-to-github.mjs",
}每次同步前,先清空 GitHub Actions 的 Secrets 和 Variables 中的环境变量(非必要,但推荐):
npm run env:clear然后同步本地 .env 文件中的环境变量到 GitHub Actions 的 Secrets 和 Variables 中:
npm run env:sync无论清空还是同步,都会输出执行结果,例如:
✅ Done in 10.9s!
📦 Variables created: 19
🔐 Secrets created: 25
⏭️ Skipped: 9如果遇到提示部分环境变量清空或者同步失败,再次执行命令就可以。
安全提示
- ⚠️ 永远不要将
.env文件提交到 Git - 确保
.env在.gitignore中 - Secrets 在 GitHub 上是加密存储的,编辑 Secrets 会显示空白,这是正常现象,不用担心。