DEV Community

Cover image for Vite 與環境變數
Leon
Leon

Posted on • Originally published at editor.leonh.space

3 2

Vite 與環境變數

Vite 是 Vue.js 作者尤雨溪開發的「下一代前端開發與構建工具」,它也是新興的前端框架 SvelteKit 預設的構建工具。

在程式專案上,我們往往會把某些重要的資訊(例如後端的 URL、第三方服務的 API 端點等)放在獨立的檔案內做管理,這個檔案習慣上會命名為 .env,再利用某些機制把 .env 內的參數載入到程式中成為可調用的變數,這些變數我們稱為「環境變數」。

環境變數

這些環境變數往往伴隨著專案的運行環境而變,在 Vite 的設計上,已經為我們預留了 development 環境(開發環境)與 production 環境(生產環境),兩者以檔名做區分,依照 Vite 的規範,開發環境的檔名是 .env.development,下面是一個最陽春的例子:

# .env.development

VITE_BACKEND_HOST=http://localhost:5000/
Enter fullscreen mode Exit fullscreen mode

而在生產環境也有這個變數,但是值是不一樣的,依照 Vite 的規範,生產環境的檔名是 .env.production,內容如下:

# .env.production

VITE_BACKEND_HOST=https://c.herokuapp.com/
Enter fullscreen mode Exit fullscreen mode

只要把這兩個檔案置於專案的根目錄下,Vite 就會自動載入,要注意的是,必須像上面的範例一樣,在變數前方有 VITE_ 的前綴 Vite 才會載入,否則會無情的忽略。

當執行 vite dev 時,會載入 .evn.development;當執行 vite buildvite preview 時,則會載入 .env.production。

調用環境變數

延續上面的例子,在程式中,我們用 import.meta.env.VITE_BACKEND_HOST 就可調用該環境變數,超級簡單。

除了我們自行定義的環境變數,Vite 還有內建四個它設定的環境變數讓我們運用:

  • import.meta.env.MODE:应用运行的模式。
  • import.meta.env.BASE_URL:部署应用时的基本 URL。它由 base 配置项决定。
  • import.meta.env.PROD:应用是否运行在生产环境。
  • import.meta.env.DEV:应用是否运行在开发环境(永远与 import.meta.env.PROD 相反)。

以上抄錄自《Vite 官方中文文档》。

實際用起來的範例:

console.log(import.meta.env.VITE_BACKEND_HOST);
Enter fullscreen mode Exit fullscreen mode

如果是在 SvelteKit 元件內則是:

<p>{import.meta.env.VITE_BACKEND_HOST}</p>
Enter fullscreen mode Exit fullscreen mode

其他前端框架應該也是類似的用法。

安全事項

前端專案意味著運行的環境是在用戶的瀏覽器,也意味著所有程式內的參數是用戶可見的(即便有混淆過),所以不適合放任何的連線帳密等私密資料,這些私密的串接,建議放到後端去做,方為上策。

參考資料

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay