點燈坊

失くすものさえない今が強くなるチャンスよ

How to read Environment Variable in Vue?

Sam Xiao's Avatar 2021-11-21

Some variable is different in development mode and production mode, like the URL of the API server. We can define them in the .env file and read the environment variable in Vue.

Version

Vue 3.2

Read .env

env000

API server is defined in .env, and we have to read it at runtime to get the URL of the API server.

Environment Variable

.env

VITE_API_SVR=http://localhost:8080

Environment variable defined in .env must have prefix VITE_.

Vue

App.vue

<script setup>
import axios from 'axios'

const API_SVR = import.meta.env.VITE_API_SVR
let articles = $ref ([])

let onClick = async _ => {
  let { data } = await axios.get (`${API_SVR}/api/articles`)
  articles = data
}
</script>

<template>
  <button @click="onClick">Get Articles</button>
  <ul>
    <li v-for="x in articles">{{ x.id }}:{{ x.title }} / {{ x.content }}</li>
  </ul>
</template>

Line 4

const API_SVR = import.meta.env.VITE_API_SVR

Use import.meta.env to get the environment variable defined in .env.

Conclusion

  • The method to read the .env environment variable is different in Webpack and Vite