Condition
發現在本地端寫的.env檔案無法部署到github pages上,所以研究了一下怎麼寫變數
Solution
step 1. 確定哪些js檔案有用到.env variable
// next.config.js
const isProd = process.env.NODE_ENV === 'production'
const withNextra = require('nextra')({
theme: 'nextra-theme-docs',
themeConfig: './theme.config.jsx',
})
const nextConfig = {
basePath: process.env.BASE_PATH,
assetPrefix: process.env.ASSET_PREFIX,
reactStrictMode: true,
output: isProd ? 'export' : 'standalone',
distDir: 'dist',
images: {
unoptimized: true,
}
}
module.exports = withNextra(nextConfig)
step 2. 在github project -> Setting -> Secrets and Variable -> Actions 設定這些變數
step 3. 在yml file 設置variable
...
- name: Build with Next.js
env:
BASE_PATH: ${{vars.BASE_PATH}}
ASSET_PREFIX: ${{vars.ASSET_PREFIX}}
run: ${{ steps.detect-package-manager.outputs.runner }} next build
...
以BASE_PATH: ${{ vars.BASE_PATH }}
為例
左邊的變數 BASE_PATH 代表從 .env 檔案設定的環境變數,這與 process.env.BASE_PATH 直接相關。
右邊的變數 ${{ vars.BASE_PATH }} 則指的是在 GitHub Actions 工作流中設置的環境變數。
[在yml檔案中]
如果是varable就用${{vars.xxxxx}}
呼叫
如果是secrets就用${{secrets.xxxxx}}
呼叫
更多的可以參考此影片