1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Viteとは

Vite(ヴィート)とは、Vue.jsの生みの親でもあるEvan Youさんによって開発されたフロントエンド開発のビルドツールです。

開発サーバーや、ビルド速度が高速であるなどの特徴があり、Webpackに代わるJavaScriptモジュールバンドラーとして注目を集めています。

環境変数を定義

Viteでは、プロジェクトのルートディレクトリに .env ファイルを作成することで、環境変数を設定することができます。

重要なルールとして、定義する環境変数には VITE_ というプレフィックスを付与する必要があります。

.env
VITE_API_URL=https://example.com/api

アプリケーションから環境変数を参照する際には、import.meta.env.環境変数名 という具合に参照します。

const apiUrl = import.meta.env.VITE_API_URL;

console.log(apiUrl); // https://example.com/api

環境変数の型を定義

Viteでは、src/ ディレクトリ配下に vite-env.d.ts というファイルを定義することで、環境変数に型を付与することができます。

これにより型補完と型チェックが有効になります。

src/vite-env.d.ts
/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_API_URL: string;
  // ...ここに追加していく
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?