問題
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に読み替えてくれるようになります。
おわりに
エラーが出た時は解決策は複雑かもと心配しましたが、意外とシンプルになおせました。