Vite+React部署GitHub Pages时.env环境变量无法访问的解决方法
解决Vite项目GitHub Pages部署时API密钥无法访问的问题
你的核心问题是没有在GitHub Actions的构建流程中注入环境变量,直接上传了本地的dist文件夹,导致Vite无法将API密钥打包进静态文件。以下是具体解决方案:
1. 修改GitHub Actions工作流,加入构建步骤
当前的static.yml跳过了项目构建环节,直接上传本地dist,这意味着仓库里的Secret根本没机会被注入到代码中。需要在依赖安装完成后添加构建命令,并将Secret作为环境变量传入:
在Install dependencies步骤之后、Setup Pages步骤之前,插入以下内容:
- name: 注入环境变量并构建项目 run: npm run build env: VITE_API_KEY: ${{ secrets.VITE_API_KEY }}
2. 正确配置仓库Secret
- 进入仓库的「Settings」→「Secrets and variables」→「Actions」→「New repository secret」
- 创建名为
VITE_API_KEY的Secret,值填写你的API密钥(必须带VITE_前缀,Vite只会识别该前缀的客户端环境变量)
3. 确认代码中环境变量的调用方式
确保代码里使用import.meta.env.VITE_API_KEY获取密钥,而非process.env——Vite在客户端环境下统一使用import.meta.env读取变量。
4. 修改后的完整工作流配置
# Simple workflow for deploying static content to GitHub Pages name: Deploy static content to Pages on: # Runs on pushes targeting the default branch push: branches: ['main'] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: # Sets the GITHUB_TOKEN permissions to allow deployment to GitHub Pages permissions: contents: read pages: write id-token: write # Allow one concurrent deployment concurrency: group: 'pages' cancel-in-progress: true jobs: # Single deploy job since we're just deploying deploy: environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 - name: Set up Node uses: actions/setup-node@v3 with: node-version: 18 cache: 'npm' - name: Install dependencies run: npm install - name: 注入环境变量并构建项目 run: npm run build env: VITE_API_KEY: ${{ secrets.VITE_API_KEY }} - name: Setup Pages uses: actions/configure-pages@v3 - name: Upload artifact uses: actions/upload-pages-artifact@v1 with: # Upload dist repository path: './dist' - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v1
为什么之前的配置无效?
- GitHub Pages是静态托管服务,运行在浏览器端,无法直接读取仓库Secret,只能在构建阶段将变量注入到静态文件中;
- 你之前直接上传本地dist,若本地构建时未正确配置
.env.production,或Action未执行构建,变量自然不会被打包进去; - Secret必须带
VITE_前缀才能被Vite识别并注入客户端代码,同时要在构建命令中显式传递该变量。
内容的提问来源于stack exchange,提问作者Giridhar Nair
相关产品推荐
相关产品推荐

