跳至主要内容

[Vite] Vite環境變數

TL;DR

介紹在Vite調整環境變數的方式。

參考資料

相關連結


環境變數檔案分類

基本上與Vue CLI相同:

.env                # loaded in all cases
.env.local # loaded in all cases, ignored by git
.env.[mode] # only loaded in specified mode
.env.[mode].local # only loaded in specified mode, ignored by git

mode則是分成production以及development

在設定時使用:

VITE_SOME_KEY=123

而使用時使用:

<script>
console.log(import.meta.env.VITE_SOME_KEY) // 123
</script>

範例

以.env檔案為範例:

.env
VITE_PATH=https://randomuser.me/api/

回到前面在安裝Vue Axios時測試所撰寫的get method,將程式碼改寫如下:

About.vue
<template>
<div class="about">
<h1>This is an about page</h1>
{{ user }}
</div>
</template>

<script>
export default {
data() {
return {
user: {}
}
},
mounted() {
const url=import.meta.env.VITE_PATH;
this.$http.get(url)
.then((response) => {
this.user=response.data.results[0]
})
}
}
</script>

<style>
@media (min-width: 1024px) {
.about {
min-height: 100vh;
display: flex;
align-items: center;
}
}
</style>