Oang Phạm
Oang Phạm

Reputation: 137

How to get env variables from env in github action .yaml in Vite project

I want to set an environment variable in github action .yaml. And I can access that variable inside my Vite project run time. Exp:

# staging.yaml - my github action file
...
env: VITE_INTERNAL = true
...
// index.vue - my Vite project
function myTest(){
    console.log(process.env.VITE_INTERNAL) // I hope to get "true" instead of "undefined"
}

Anyone can help me, please. Thanks a lot!

Upvotes: 6

Views: 8202

Answers (2)

tony19
tony19

Reputation: 138506

To set an environment variable in a GitHub Action YAML, you can use env, jobs.<job_id>.env, or jobs.<job_id>.steps[*].env:

name: Build

permissions:
  contents: read
  issues: read
  checks: write
  pull-requests: write

on: push

# 👇 global env
env:
  VITE_INTERNAL: true

jobs:
  build:
    runs-on: ubuntu-latest
    # 👇 or job-level env
    env:
      VITE_INTERNAL: true

    steps:
    - uses: actions/checkout@v3
    - uses: actions/setup-node@v3
      with:
        node-version: 18.x
        cache: 'npm'
    - name: Install dependencies
      run: npm i
    - name: Build
      run: npm run build

      # 👇 or step-level env
      env:
        VITE_INTERNAL: true

To access the environment variable from JavaScript, use import.meta.env.VITE_INTERNAL (not process.env.VITE_INTERNAL).

GitHub demo

Upvotes: 7

user633440
user633440

Reputation:

You can read the docs here, but to expose env variables, you can do it like the following.

.env

VITE_INTERNAL = true

.yaml

console.log(import.meta.env.VITE_INTERNAL)

Upvotes: 2

Related Questions