5
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?

import.meta.env cannot read properties of undefined

Posted at

問題

ReactとViteの環境下でjestとreact-testing-libraryを使用してtestをしたときにエラーが発生していました。

import.meta.env cannot read properties of undefined

解決方法

Viteを使用してsupabaseの環境変数設定をする場合、import.meta.envを使用する必要があります。

ただ、このままだと上記エラーが出てsupabaseUrlの読み込みができないため、vite.config.jsを以下のように変更しました。

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import env from "vite-plugin-env-compatible";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react(), env({ prefix: "VITE", mountedPath: "process.env" })],
});

また、supabaseの環境変数設定を行っているところをimport.meta.envからprocess.envに変更しました。

import { createClient } from "@supabase/supabase-js";

export const supabase = createClient(
  process.env.VITE_SUPABASE_URL,
  process.env.VITE_SUPABASE_ANON_KEY
);

vite.config.jsにplugins: [react(), env({ prefix: "VITE", mountedPath: "process.env" })]とすることで、VITEでimport.meta.envが必要なところをprocess.envに読み替えてくれるようになります。

おわりに

エラーが出た時は解決策は複雑かもと心配しましたが、意外とシンプルになおせました。

5
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
5
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?