From 648cb0a6596d349a0fd61edab5c6857b485e0776 Mon Sep 17 00:00:00 2001 From: Pavindu Lakshan Date: Thu, 16 Jan 2025 18:56:20 +0530 Subject: [PATCH] Load vite app configurations from environment variables --- samples/asgardeo-react-app/.env | 3 ++ samples/asgardeo-react-app/vite.config.ts | 66 +++++++++++++---------- 2 files changed, 42 insertions(+), 27 deletions(-) create mode 100644 samples/asgardeo-react-app/.env diff --git a/samples/asgardeo-react-app/.env b/samples/asgardeo-react-app/.env new file mode 100644 index 0000000..0d19819 --- /dev/null +++ b/samples/asgardeo-react-app/.env @@ -0,0 +1,3 @@ +PORT=3000 +HOST="localhost" +HTTPS=true \ No newline at end of file diff --git a/samples/asgardeo-react-app/vite.config.ts b/samples/asgardeo-react-app/vite.config.ts index fb00d1d..60c7bc4 100644 --- a/samples/asgardeo-react-app/vite.config.ts +++ b/samples/asgardeo-react-app/vite.config.ts @@ -1,32 +1,44 @@ -import { defineConfig } from 'vite' -import react from '@vitejs/plugin-react' +import { defineConfig, loadEnv, UserConfig } from 'vite'; +import react from '@vitejs/plugin-react'; import fs from 'fs'; import path from 'path'; -export default defineConfig({ - plugins: [ - react() - ], - optimizeDeps: { - include: [ - '@asgardeo/auth-react', - 'react/jsx-runtime', - 'react-router', - 'react-router-dom', - 'react', - ], - }, - server: { - https: { - key: fs.readFileSync(path.resolve(__dirname, 'public', 'cert', 'localhost-key.pem')), - cert: fs.readFileSync(path.resolve(__dirname, 'public', 'cert', 'localhost-cert.pem')), +export default defineConfig(({ mode }) => { + + const env = loadEnv(mode, process.cwd(), '') + + // Explicitly define the configuration type + const config: UserConfig = { + plugins: [react()], + optimizeDeps: { + include: [ + '@asgardeo/auth-react', + 'react/jsx-runtime', + 'react-router', + 'react-router-dom', + 'react', + ], + }, + server: { + host: env.HOST, + port: parseInt(env.PORT || '3000', 10), }, - host: 'localhost', - port: 3000 - }, - build: { - commonjsOptions: { - include: [ /react/ ], - }, + build: { + commonjsOptions: { + include: [/react/], + }, + }, + }; + + if (env.HTTPS === 'true') { + config.server = { + ...config.server, + https: { + key: fs.readFileSync(path.resolve(__dirname, 'public', 'cert', 'localhost-key.pem')), + cert: fs.readFileSync(path.resolve(__dirname, 'public', 'cert', 'localhost-cert.pem')), + }, + }; } -}) + + return config; +});