运行 Next JS build command on Github Actions 时如何使用环境变量

How to use environment variables when running Next JS build command on Github Actions

如何让 Github 操作访问我的 .env.local 文件以构建我的 Next JS 应用程序而不暴露我的 github 存储库中的 .env.local 文件?

当前,使用 Github 操作构建时,构建将无法访问 .env.local(因为该文件未推送到 Github 存储库)。

我有一个 next.config.js 文件看起来像

/** @type {import('next').NextConfig} */

const isProd = process.env.NEXT_PUBLIC_ENVIRONMENT === "PROD";

const nextConfig = {
  reactStrictMode: true,
  basePath: isProd ? '/XXX' : '', 
  assetPrefix: isProd ? '/XXX' : '' 
}

module.exports = nextConfig

还有一个 deploy.workflow.yaml 用于 Github 看起来像

的操作
name: deploy-workflow
on
  push:
    branches:
      - main # Pushing a commit to the master branch is the event that triggers the workflow.
jobs:
  deploy-job:
    runs-on: ubuntu-latest # Configures the job to run on a fresh Ubuntu Linux virtual machine hosted by GitHub (aka the Runner).
    steps:
      - uses: actions/checkout@v2 # The action to check out the repo and download the code into the Runner. 
      - uses: actions/setup-node@v2 # The action to install Node.js in the Runner, and allow us to run npm commands.
        with:
          node-version: '16'
      - uses: actions/cache@v2 # This action caches the node_modules folder across builds, and makes the Runner use the cache as long as package-lock.json doesn’t change.
        with:
        # Next.js stores its cache in the .next/cache directory. This will persist the cache across builds for faster application rebuilds. E.g., if I only updated my codebase but not the dependencies, this avoids re-bundling the dependencies.
         path: |
           ${{ github.workspace }}/node_modules
           ${{ github.workspace }}/.next/cache
         # Generate a new cache whenever packages or source files change.
         key: ${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json') }}-${{ hashFiles('**/*.js') }}
         # If source files changed but packages didn't, rebuild from a prior cache. 
         restore-keys: |
           ${{ runner.os }}-nextjs-${{ hashFiles('**/package-lock.json') }}-
      - run: npm install
      - run: npm run build # Builds the static files
      - uses: stefanzweifel/git-auto-commit-action@v4 # This action will commit changes made in the Runner environment, and push the commit to the GitHub repo. The default commit message will be “Automated publish”.
        with:
          commit_message: Automated publish
      - name: Deploy 
        uses: JamesIves/github-pages-deploy-action@4.1.5
        with:
          branch: gh-pages
          folder: output

除了 .env.local 文件(通常用于包含仅本地需要的内容)之外,您还可以使用文件 .env.env.development.env.production.然后可以签入这些文件。

您的 .env 文件可以包含全局默认值(例如一些配置)。对于其他人,您可以覆盖特定于该环境的配置。

.env.local 文件相反,通常会签入其他三个文件。

查看他们的 docs 了解更多信息。