From 1cdcc08eae3d364912324afba3a848eb04f1b6aa Mon Sep 17 00:00:00 2001 From: Anthony <47945770+Tony0410@users.noreply.github.com> Date: Thu, 27 Nov 2025 21:19:46 +0800 Subject: [PATCH] Use Vite env key for Gemini --- README.md | 2 +- services/geminiService.ts | 8 ++++++-- tsconfig.json | 2 +- vite-env.d.ts | 1 + vite.config.ts | 16 +++------------- 5 files changed, 12 insertions(+), 17 deletions(-) create mode 100644 vite-env.d.ts diff --git a/README.md b/README.md index c399b6a..ed19cfd 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,6 @@ View your app in AI Studio: https://ai.studio/apps/drive/1a8wkyYOUvPDWvUXbrtN2dz 1. Install dependencies: `npm install` -2. Set the `GEMINI_API_KEY` in [.env.local](.env.local) to your Gemini API key +2. Set the `VITE_API_KEY` in [.env.local](.env.local) to your Gemini API key (e.g., `VITE_API_KEY=your_key_here`) 3. Run the app: `npm run dev` diff --git a/services/geminiService.ts b/services/geminiService.ts index 5ba85fb..2c8a8da 100644 --- a/services/geminiService.ts +++ b/services/geminiService.ts @@ -2,10 +2,14 @@ import { GoogleGenAI, Modality } from '@google/genai'; import { VoiceName } from '../types'; const getAiClient = () => { - const apiKey = process.env.API_KEY; + const apiKey = import.meta.env.VITE_API_KEY; + if (!apiKey) { - throw new Error("API Key is missing"); + throw new Error( + "Gemini API key is missing. Set VITE_API_KEY in your .env.local file (e.g., VITE_API_KEY=your_key_here)." + ); } + return new GoogleGenAI({ apiKey }); }; diff --git a/tsconfig.json b/tsconfig.json index 0f950d7..5bcf8cd 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -16,6 +16,6 @@ "noUnusedParameters": false, "noFallthroughCasesInSwitch": true }, - "include": ["**/*.ts", "**/*.tsx"], + "include": ["**/*.ts", "**/*.tsx", "**/*.d.ts"], "exclude": ["node_modules"] } \ No newline at end of file diff --git a/vite-env.d.ts b/vite-env.d.ts new file mode 100644 index 0000000..11f02fe --- /dev/null +++ b/vite-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/vite.config.ts b/vite.config.ts index 15cd120..f43fbe9 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,16 +1,6 @@ -import { defineConfig, loadEnv } from 'vite'; +import { defineConfig } from 'vite'; import react from '@vitejs/plugin-react'; -export default defineConfig(({ mode }) => { - // Load env file based on `mode` in the current working directory. - const env = loadEnv(mode, (process as any).cwd(), ''); - - return { - plugins: [react()], - define: { - // This allows the app code to continue using process.env.API_KEY - // even though it is running in the browser. - 'process.env.API_KEY': JSON.stringify(env.API_KEY) - } - }; +export default defineConfig({ + plugins: [react()] }); \ No newline at end of file