### Docker Entrypoint Example Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/cli-commands.md An example of how to use `npx vite-envs` as an entrypoint in a Dockerfile after the build stage to perform post-build injection before starting the web server. ```dockerfile FROM node:18-alpine AS builder WORKDIR /app COPY . . RUN npm install && npm run build FROM nginx:alpine COPY --from=builder /app/dist /usr/share/nginx/html WORKDIR /usr/share/nginx/html # Run injection script before starting nginx ENTRYPOINT sh -c "npx vite-envs && nginx -g 'daemon off;'" ``` -------------------------------- ### GitHub Actions CI/CD Workflow Example Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Example GitHub Actions workflow for building and deploying an application. It includes steps for checking out code, setting up Node.js, installing dependencies, building the app, building a Docker image, pushing to a registry, and deploying using kubectl. ```yaml # .github/workflows/deploy.yml name: Build and Deploy on: push: branches: [main] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: '18' - run: npm ci - run: npm run build - name: Build Docker image run: docker build -t myapp:${{ github.sha }} . - name: Push to registry run: | docker tag myapp:${{ github.sha }} myregistry/myapp:latest docker push myregistry/myapp:latest - name: Deploy run: | kubectl set image deployment/myapp \ myapp=myregistry/myapp:latest ``` -------------------------------- ### CI/CD Pipeline Example for Build and Type Updates Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/cli-commands.md An example of a GitHub Actions workflow demonstrating build, type updates using vite-envs, and Docker image generation. ```yaml # Example: GitHub Actions - name: Build run: npm run build - name: Update Types run: npx vite-envs update-types - name: Generate Docker Image run: docker build -t myapp:latest . ``` -------------------------------- ### Example .env.declaration and .env Files Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Demonstrates how to structure declaration and local environment files. The `.env.declaration` file is tracked in git, while `.env` is git-ignored. ```bash # .env.declaration (tracked in git) API_URL= FEATURE_FLAGS= LOG_LEVEL= # .env (git-ignored, local development) API_URL=http://localhost:3000 FEATURE_FLAGS={"auth":true} LOG_LEVEL=debug ``` -------------------------------- ### Base64 Decode Syntax Example Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/helper-functions.md Demonstrates the syntax for Base64 decoding values within .env files using vite-envs. ```bash # .env SECRET_KEY=vite-envs:b64Decode(Y3JlZGVudGlhbHM=) ``` ```javascript const value = parseEnvValue("vite-envs:b64Decode(Y3JlZGVudGlhbHM=)"); console.log(value); // "credentials" ``` -------------------------------- ### Docker Run Command Example Source: https://github.com/garronej/vite-envs/blob/main/README.md Use this command to run a Docker container and set environment variables that vite-envs can access. ```bash docker run --env FOO="xyz" my-org/my-vite-app ``` -------------------------------- ### EJS Template Examples with Environment Variables Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/helper-functions.md Illustrates various ways to use environment variables and utilities like JSON5 within EJS templates rendered by `renderHtmlAsEjs`. Examples include accessing variables, using JavaScript expressions, conditional logic, loops, and JSON5 stringification. ```html <%= import.meta.env.APP_NAME %> <% if (import.meta.env.ENABLE_ANALYTICS) { %> <% } %> <% import.meta.env.SCRIPT_URLS.forEach(url => { %> <% }); %> ``` -------------------------------- ### HTML Placeholder Syntax Example Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/helper-functions.md Demonstrates the `%VAR_NAME%` syntax used by `substituteHtmPlaceholders` for replacing environment variables directly within HTML content. ```html %APP_TITLE% ``` -------------------------------- ### Documentation File Manifest Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/README.md Lists the available documentation files within the project, including README, API references, and configuration guides. ```text /output ├── README.md (this file) ├── types.md ├── configuration.md ├── errors.md ├── module-architecture.md ├── usage-patterns.md └── api-reference/ ├── overview.md ├── viteEnvs.md ├── cli-commands.md ├── helper-functions.md ``` -------------------------------- ### ViteEnvsMeta JSON Serialization Example Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/types.md Illustrates the structure and content of the .vite-envs.json file, showing how ViteEnvsMeta is serialized for runtime use. ```json { "version": "4.7.1", "assetsUrlPath": "/assets", "htmlPre": "...", "declaredEnv": { "API_URL": "", "DATABASE_HOST": "", "ENABLE_LOGGING": "true", "PORT": "3000" }, "computedEnv": { "BUILD_TIME": "2024-01-15T10:30:00Z", "BUILT_BY": "ci" }, "baseBuildTimeEnv": { "BASE_URL": "/", "PROD": true, "DEV": false, "SSR": false }, "nameOfTheGlobal": "__VITE_ENVS" } ``` -------------------------------- ### Basic viteEnvs Setup Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/viteEnvs.md Integrate the viteEnvs plugin into your Vite configuration for basic environment variable handling. ```typescript import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import { viteEnvs } from "vite-envs"; export default defineConfig({ plugins: [viteEnvs(), react()] }); ``` -------------------------------- ### Host Environment Variable Override Example Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/configuration.md Demonstrates how host system environment variables can override .env values for declared variables. ```bash # Host environment (Docker, shell, CI/CD, etc.) export API_URL=https://staging.example.com export LOG_LEVEL=debug # These override .env values if the variables are declared in .env ``` -------------------------------- ### Docker Deployment with Runtime Environment Variables Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/configuration.md Example Dockerfile demonstrating how to build a Vite application and inject production environment variables at runtime using `ENV` directives and an `ENTRYPOINT` script that executes `vite-envs.sh`. ```dockerfile # Dockerfile FROM node:18 AS builder WORKDIR /app COPY . . RUN npm install && npm run build FROM nginx:alpine COPY --from=builder /app/dist /usr/share/nginx/html WORKDIR /usr/share/nginx/html # Production values injected at runtime ENV API_URL="https://api.example.com" ENV LOG_LEVEL="info" ENTRYPOINT sh -c "./vite-envs.sh && nginx -g 'daemon off;'" ``` -------------------------------- ### Declaration File (.env) Example Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/configuration.md Defines the schema for environment variables. Variables with values act as defaults, while empty values require runtime provision. Supports Base64 decoding. ```bash # .env (or custom declarationFile) # Variables with values act as defaults APP_NAME=MyApp APP_VERSION=1.0.0 THEME_COLOR=#007bff # Variables with empty values must be provided at runtime API_URL= DATABASE_HOST= LOG_LEVEL= # Variables can be booleans or numbers ENABLE_ANALYTICS=true MAX_RETRIES=3 # Base64-encoded values can be decoded at build time SECRET_KEY=vite-envs:b64Decode(Y3JlZGVudGlhbHM=) ``` -------------------------------- ### .env.local File Example Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/configuration.md Contains runtime-specific values that override defaults defined in the .env file. This file should not be committed to version control. ```bash # .env.local (generated at runtime, not in repo) API_URL=https://api.production.example.com DATABASE_HOST=db.production.internal ``` -------------------------------- ### Base64 Encoded Environment Value Example Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/module-architecture.md Demonstrates how to use Base64 encoding for storing binary or multiline values within .env files, decoded by vite-envs. ```dotenv SECRET=vite-envs:b64Decode(c2VjcmV0) ``` -------------------------------- ### Usage Example for Global Environment Script Generation Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/helper-functions.md Shows how to use the getScriptThatDefinesTheGlobal function to create a script for injecting environment variables into the global scope. ```typescript import { getScriptThatDefinesTheGlobal } from "vite-envs/dist/getScriptThatDefinesTheGlobal"; const script = getScriptThatDefinesTheGlobal({ env: { API_URL: "https://api.example.com", DEBUG: false }, nameOfTheGlobal: "__VITE_ENVS" }); console.log(script); // ``` -------------------------------- ### Inject Environment Variables at Runtime Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/README.md This CLI command injects environment variables at runtime. Ensure it's run before your web server starts. ```bash # Inject environment variables at runtime npx vite-envs ``` -------------------------------- ### Install EJS or Disable EJS Rendering Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/errors.md If the EJS module fails to load with indexAsEjs: true and EJS is not a dependency, install EJS using npm or disable EJS rendering in vite.config.ts. ```bash # Install EJS if not present npm install ejs ``` ```typescript // vite.config.ts viteEnvs({ indexAsEjs: false // Use %VAR% placeholders instead }) ``` -------------------------------- ### Declare Environment Variables in .env Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/errors.md Add environment variable declarations to your .env file. This example shows how to declare API_URL, APP_NAME, and DEBUG. ```dotenv # .env API_URL= APP_NAME=MyApp DEBUG=true ``` -------------------------------- ### Execute vite-envs.sh on Alpine Linux Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/errors.md When deploying on Alpine Linux, explicitly use /bin/sh to execute vite-envs.sh as bash may not be available by default. Alternatively, install bash if needed. ```bash # ✓ Use /bin/sh explicitly (sh is available) ENTRYPOINT sh -c "./vite-envs.sh && ..." # Or use /bin/bash if available RUN apk add --no-cache bash ENTRYPOINT bash -c "./vite-envs.sh && ..." ``` -------------------------------- ### Main Plugin API Reference Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/MANIFEST.md Reference for the main vite-envs plugin function, detailing its signature, parameters, return type, and various usage examples. ```APIDOC ## viteEnvs() ### Description The main plugin API reference for vite-envs. This function is the entry point for integrating vite-envs into your Vite project. ### Function Signature `viteEnvs(options?: ViteEnvsOptions): Plugin` ### Parameters #### Options (`ViteEnvsOptions`) - **computedEnv** (object | async function) - Optional - Allows defining computed environment variables, which can be static objects or asynchronous functions. - **declarationFile** (string) - Optional - Path to the declaration file to be generated. - **indexAsEjs** (boolean) - Optional - If true, the index.html will be treated as an EJS template. - **ambientModuleDeclarationFilePath** (string) - Optional - Path for ambient module declarations. - **nameOfTheGlobal** (string) - Optional - The name of the global variable to expose environment variables. ### Return Type - `Plugin` - Returns a Vite plugin object that can be added to the Vite configuration. ### Usage Examples - Basic usage - Computed environment variables (static and async) - Using EJS for templating - Defining custom global variables ``` -------------------------------- ### Docker Compose for Multi-Service Applications Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Define and manage multi-container Docker applications using Docker Compose. This example shows an app service, an API service, and a database service. ```yaml # docker-compose.yml version: '3.8' services: app: build: context: . dockerfile: Dockerfile ports: - "3000:80" environment: API_URL: http://localhost:8000 LOG_LEVEL: info ENABLE_ANALYTICS: "false" depends_on: - api api: image: myapi:latest ports: - "8000:8000" environment: DATABASE_URL: postgresql://postgres:password@db:5432/mydb db: image: postgres:15 environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: password POSTGRES_DB: mydb ``` -------------------------------- ### Environment Variable Declaration Example Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/viteEnvs.md Declare environment variables in a `.env` file. Variables with empty values act as declaration-only and require runtime values. Variables with values serve as defaults. ```bash # .env API_URL= DATABASE_HOST= ENABLE_LOGGING=true PORT=3000 ``` -------------------------------- ### Auto-Generated vite-env.d.ts File Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/configuration.md Example of the TypeScript ambient module declaration file generated by the plugin. User-defined extensions are preserved between specific markers. ```typescript /// type ImportMetaEnv = { // Auto-generated by `npx vite-envs update-types` APP_NAME: string; API_URL: string; ENABLE_ANALYTICS: boolean; MAX_RETRIES: number; // @user-defined-start // Add custom extensions here between these markers CUSTOM_VAR: CustomType; // @user-defined-end }; interface ImportMeta { // Auto-generated by `npx vite-envs update-types` url: string; readonly hot?: import('vite-envs/types/hot').ViteHotContext; readonly env: ImportMetaEnv; glob: import('vite-envs/types/importGlob').ImportGlobFunction; } ``` -------------------------------- ### Example of Transformed and Untransformed Variables Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/errors.md This example demonstrates how vite-envs transforms declared variables like API_URL but leaves undeclared variables like UNKNOWN_VAR unchanged. ```typescript // src/main.ts import.meta.env.API_URL; // ✓ Transformed (declared in .env) import.meta.env.UNKNOWN_VAR; // ✗ Not transformed (not declared) ``` -------------------------------- ### Build and Deploy with Environment Variables Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Build your application locally and then deploy it to Docker. Run the Docker container, passing environment variables using the -e flag. ```bash # Build locally (types generated automatically) npm run build # Deploy to Docker docker build -t myapp:latest . # Run with environment variables docker run \ -e API_URL="https://api.production.example.com" \ -e LOG_LEVEL="error" \ myapp:latest ``` -------------------------------- ### CLI Entry Point and Commands Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/overview.md The `vite-envs` binary serves as the CLI entry point, offering commands for updating types and performing post-build injection. The main logic is in `src/bin/main.ts`. ```plaintext Binary: vite-envs Location: src/bin/main.ts Commands: - vite-envs update-types - vite-envs (no args) - post-build injection ``` -------------------------------- ### Create Declaration File Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Define your environment variables in a .env file in the project root. These variables will be available through import.meta.env. ```bash # .env (in project root) API_URL= API_TIMEOUT=30000 ENABLE_ANALYTICS=false APP_NAME=MyApp LOG_LEVEL=info ``` -------------------------------- ### Docker Build and Run Commands Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Commands for building a Docker image and running a Vite application container with specified environment variables. ```bash docker build -t myapp:1.0.0 . # Run with different configurations docker run \ -e API_URL="https://api.example.com" \ -p 80:80 \ myapp:1.0.0 ``` -------------------------------- ### Build Time Data Flow Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/README.md Illustrates the sequence of operations during the build process, from parsing .env files to transforming import.meta.env. ```text .env file → parseDotEnv() → mergedEnv → Generate type definitions in vite-env.d.ts → Transform import.meta.env in source files → Generate vite-envs.sh script → Write .vite-envs.json metadata ``` -------------------------------- ### Mocking Environment Variables in Tests (Initial Approach) Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Demonstrates an initial approach to testing environment variables by saving and restoring `import.meta.env`. Note that `import.meta.env` is read-only at runtime, suggesting a better pattern is needed. ```typescript // src/__tests__/api.test.ts import { describe, it, expect, beforeEach } from 'vitest'; describe('API Configuration', () => { let originalEnv: typeof import.meta.env; beforeEach(() => { // Save original originalEnv = { ...import.meta.env }; }); it('should use API_URL from environment', () => { // Note: import.meta.env is read-only at runtime // For testing, you may need to: // 1. Extract configuration into a function // 2. Mock that function in tests const apiUrl = import.meta.env.API_URL; expect(apiUrl).toBeDefined(); }); }); ``` -------------------------------- ### Docker Best Practice for Runtime Injection Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/overview.md Illustrates how to avoid including sensitive .env files in Docker images by injecting environment variables at runtime using a shell script. ```dockerfile # Do NOT include sensitive .env in image # Inject at runtime instead FROM nginx:alpine COPY --from=builder /app/dist /usr/share/nginx/html # Sensitive values provided at runtime ENV API_TOKEN="" # Required at runtime ENV DATABASE_URL="" ENTRYPOINT sh -c "./vite-envs.sh && nginx" ``` -------------------------------- ### Accessing Custom Global Environment Variable Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/viteEnvs.md Example of how to access environment variables stored in a custom global variable (e.g., `__MY_APP_ENV`) within your application code. ```typescript const apiUrl = window.__MY_APP_ENV.API_URL; ``` -------------------------------- ### Dockerfile Modification for Runtime Env Injection Source: https://github.com/garronej/vite-envs/blob/main/README.md Modify your Dockerfile to execute the generated vite-envs.sh script before starting your web server, enabling runtime environment variable injection. ```diff -CMD ["nginx", "-g", "daemon off;"] +ENTRYPOINT sh -c "./vite-envs.sh && nginx -g 'daemon off;'" ``` -------------------------------- ### Runtime Data Flow Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/README.md Details the steps involved in injecting environment variables at runtime, including reading metadata and updating index.html. ```text .vite-envs.json → Read environment variables → Base64 encode values → Update index.html with injected script → Create swEnv.js for service workers ``` -------------------------------- ### Build Stage in GitLab CI Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Defines the build stage for a GitLab CI pipeline. It uses a Node.js image to install dependencies and build the project, then archives the distribution files. ```yaml stages: - build - push - deploy build: stage: build image: node:18 script: - npm ci - npm run build artifacts: paths: - dist/ ``` -------------------------------- ### Basic Vite Configuration with vite-envs Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/configuration.md A minimal vite.config.ts file demonstrating how to integrate the vite-envs plugin with other Vite plugins like react. ```typescript // vite.config.ts import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import { viteEnvs } from "vite-envs"; export default defineConfig({ plugins: [viteEnvs(), react()], }); ``` -------------------------------- ### CLI Commands Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/MANIFEST.md Documentation for the command-line utilities provided by vite-envs, including type updating and post-build injection. ```APIDOC ## CLI Commands ### `vite-envs update-types` #### Description This command triggers the generation of type definition files for your environment variables. It ensures type safety by creating or updating declaration files. #### Usage ```bash vite-envs update-types ``` #### Behavior - Triggers type generation. - Ensures Windows compatibility. - Includes error handling for the generation process. ### `vite-envs` Post-Build Injection #### Description This command performs a post-build injection of environment variables. It's useful for scenarios like Docker deployments where environment variables need to be injected after the build process. #### Behavior - Injects environment variables after the build. - Merges environment variables. - Generates metadata structure for injection. - Prerequisites and behavior are detailed for usage in Docker. ``` -------------------------------- ### viteEnvs with Custom Global Name Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/viteEnvs.md Configure viteEnvs to use a custom global variable name instead of the default `__VITE_ENVS`. This is useful for avoiding conflicts in micro-frontend architectures or specific project setups. ```typescript import { defineConfig } from "vite"; import { viteEnvs } from "vite-envs"; export default defineConfig({ plugins: [ viteEnvs({ nameOfTheGlobal: "__MY_APP_ENV" }), react() ] }); ``` -------------------------------- ### Multi-stage Docker Build for Vite Application Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/overview.md Provides a Dockerfile pattern for a multi-stage build, separating the build environment from the runtime environment to create a clean production image. ```dockerfile # Multi-stage build FROM node:18 AS builder WORKDIR /app COPY . . RUN npm install && npm run build # Runtime stage (clean image) FROM nginx:alpine COPY --from=builder /app/dist /usr/share/nginx/html ENTRYPOINT sh -c "./vite-envs.sh && nginx -g 'daemon off;'" ``` -------------------------------- ### Standard Dockerfile for Vite Application Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md A Dockerfile for building and running a Vite application, including multi-stage builds and environment variable injection. ```dockerfile # Dockerfile FROM node:18-alpine AS builder WORKDIR /app # Copy source COPY package.json package-lock.json ./ COPY src ./src COPY public ./public COPY index.html vite.config.ts tsconfig.json ./ COPY .env ./ # Build application RUN npm ci && npm run build # Production image FROM nginx:alpine # Copy built application COPY --from=builder /app/dist /usr/share/nginx/html # Make vite-envs.sh executable RUN chmod +x /usr/share/nginx/html/vite-envs.sh # Set working directory WORKDIR /usr/share/nginx/html # Configure nginx (optional) COPY nginx.conf /etc/nginx/nginx.conf # Run injection script before starting nginx ENTRYPOINT sh -c "./vite-envs.sh && nginx -g 'daemon off;'" ``` -------------------------------- ### Configure Unique Global Names in Monorepo Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/errors.md In a monorepo setup, to prevent global name conflicts when multiple packages use the default `__VITE_ENVS` global name, assign a unique name to each package's environment. ```typescript // Each package uses unique name viteEnvs({ nameOfTheGlobal: "__PACKAGE_A_ENV" // In package A }) // In package B viteEnvs({ nameOfTheGlobal: "__PACKAGE_B_ENV" // Unique name }) ``` -------------------------------- ### Reading ViteEnvsMeta at Runtime Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/types.md Demonstrates how to read and parse the ViteEnvsMeta JSON file at runtime to access build information and configuration. ```typescript import type { ViteEnvsMeta } from "vite-envs"; import { viteEnvsMetaFileBasename } from "vite-envs"; import * as fs from "fs"; const metadata: ViteEnvsMeta = JSON.parse( fs.readFileSync(viteEnvsMetaFileBasename, 'utf8') ); console.log(`Built with vite-envs ${metadata.version}`); console.log(`Assets path: ${metadata.assetsUrlPath}`); console.log(`Global variable: window.${metadata.nameOfTheGlobal}`); ``` -------------------------------- ### Vite Plugin Lifecycle: transformIndexHtml Hook (pre) Actions Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/overview.md The `transformIndexHtml` hook processes `index.html` before the dev server starts. It can render HTML as EJS, substitute `%VAR%` placeholders, and inject an environment access script into the ``. ```plaintext Execution: Process index.html before dev server Actions: 1. If indexAsEjs: Render HTML as EJS template 2. Substitute %VAR% placeholders with env values 3. Inject environment access script into 4. Return processed HTML for dev server ``` -------------------------------- ### Build Application and Verify .vite-envs.json Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/errors.md Before running the npx vite-envs command, ensure your application is built and the .vite-envs.json file exists in the dist directory. This file is generated during the build process. ```bash # Build the application first npm run build # Verify the file exists ls -la dist/.vite-envs.json # Then run injection npx vite-envs ``` -------------------------------- ### Project File Organization Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/MANIFEST.md Illustrates the directory structure for the vite-envs project documentation and source files. ```text /output ├── README.md (main index) ├── types.md (type definitions) ├── configuration.md (setup options) ├── errors.md (error reference) ├── module-architecture.md (internals) ├── usage-patterns.md (examples) └── api-reference/ ├── overview.md (architecture) ├── viteEnvs.md (main API) ├── cli-commands.md (CLI reference) └── helper-functions.md (utilities) ``` -------------------------------- ### Using Different Declaration Files Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Configure Vite Envs to use a separate `.env.declaration` file, allowing you to keep local `.env` files git-ignored. ```typescript // vite.config.ts export default defineConfig({ plugins: [ viteEnvs({ // Use separate .env.declaration file (keep .env local/git-ignored) declarationFile: ".env.declaration", }), ], }); ``` -------------------------------- ### npm Script Integration for Build and Deployment Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/cli-commands.md Defines npm scripts for building the project, updating types post-build, and preparing for deployment using vite-envs. ```json { "scripts": { "build": "vite build", "postbuild": "npx vite-envs update-types", "predeploy": "npm run build && npx vite-envs" } } ``` -------------------------------- ### Create .env Declaration File Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/errors.md Create the .env file in your project root if it does not exist. This file is used to declare environment variables for vite-envs. ```bash touch .env ``` -------------------------------- ### Vite-Envs Shell Script Generation for Runtime Injection Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/module-architecture.md Illustrates the structure of the vite-envs.sh script used for runtime environment variable injection. It details steps for reading HTML, encoding variables, performing replacements, and generating the injection script. ```bash #!/bin/sh # 1. Helper function for string replacement replaceAll() { ... } # 2. Read base64-encoded HTML html=$(echo "..." | base64 -d) # 3. For each environment variable: # - Define shell variable (from env or default) # - Base64 encode it VAR_NAME=$(...) VAR_NAME_base64=$(...) # 4. Apply all replacements processedHtml=$(replaceAll "$processedHtml" "%VAR_NAME%" "...") # 5. Build JSON of base64-encoded values json="..." # 6. Generate environment injection script script=" ``` ```typescript viteEnvs({ indexAsEjs: false, // Default - use %VAR% syntax }) ``` ```bash # .env APP_NAME=My Application APP_DESCRIPTION=A sample Vite app THEME_COLOR=#007bff ``` -------------------------------- ### TypeScript Configuration Before Plugin Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/configuration.md Shows the default Vite client types configuration in tsconfig.json. ```json { "compilerOptions": { "types": ["vite/client"] } } ``` -------------------------------- ### Configure Custom Paths for Declaration and Ambient Files Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/configuration.md Customize the paths for declaration files and ambient module declarations using `declarationFile` and `ambientModuleDeclarationFilePath`. This allows you to organize your environment configuration and type definitions. ```typescript // vite.config.ts export default defineConfig({ plugins: [ viteEnvs({ declarationFile: "config/.env.declaration", ambientModuleDeclarationFilePath: "src/types/env.d.ts", nameOfTheGlobal: "__CUSTOM_ENV" }), react() ], }); ``` -------------------------------- ### Docker Build and Push Stage in GitLab CI Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Configures the push stage for a GitLab CI pipeline to build a Docker image and push it to a registry. Requires Docker-in-Docker service. ```yaml docker_build: stage: push image: docker:latest services: - docker:dind script: - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA . - docker push $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA ``` -------------------------------- ### Ensure vite-envs.sh Exists and is Executable Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/errors.md In Dockerfile deployments, verify that the vite-envs.sh script exists at the expected path and has execute permissions. Incorrect paths or missing permissions will result in a 'command not found' error. ```dockerfile # Ensure script exists and is executable RUN ls -la /usr/share/nginx/html/vite-envs.sh RUN chmod +x /usr/share/nginx/html/vite-envs.sh # Or use sh explicitly ENTRYPOINT sh -c "sh ./vite-envs.sh && nginx" ``` -------------------------------- ### parseDotEnv Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/helper-functions.md Parses environment variable files (.env format) and returns a record of key-value pairs. It handles special syntax and throws errors for invalid files. ```APIDOC ## parseDotEnv ### Description Parses environment variable files (.env format) and returns a record of key-value pairs. It handles special syntax and throws errors for invalid files. ### Function Signature ```typescript export function parseDotEnv(params: { path: string }): Record ``` ### Parameters #### Path Parameters - **params.path** (string) - Required - Absolute path to .env file to parse ### Return Type `Record` — Object with variable names as keys and their values as strings. All values are run through `parseEnvValue()` to handle special syntax. ### Behavior 1. Uses the `dotenv` library to parse the file 2. Processes each value with `parseEnvValue()` to handle vite-envs syntax 3. Throws error if file cannot be parsed ### Throws - Error: "Could not parse {path}" if the file exists but is invalid ### Usage Example ```typescript import { parseDotEnv } from "vite-envs/dist/parseDotEnv"; // Internal use const envVars = parseDotEnv({ path: "/app/.env" }); console.log(envVars); // { API_URL: "https://api.example.com", PORT: "3000" } ``` ``` -------------------------------- ### Environment Merging Algorithm Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/module-architecture.md Illustrates the order of operations for merging environment variables, prioritizing runtime overrides and declared variables. ```typescript mergedEnv = { // 1. Computed and base, filtered by declaredEnv ...filtered(baseBuildTimeEnv + computedEnv), // 2. Declared variables not overridden by computedEnv ...declaredEnv.filter(key not in computedEnv || value !== ""), // 3. Include .env if it's different from declarationFile ...dotEnv, // 4. Runtime overrides ...dotEnvLocal, // 5. process.env for declared variables ...process.env.filter(key in declaredEnv) } ``` -------------------------------- ### Service Worker Environment Script Usage Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/module-architecture.md Shows how to import and use environment variables from the generated `swEnv.js` file within a service worker context. ```javascript // In service worker importScripts('swEnv.js'); const url = self.__VITE_ENVS.API_URL; ``` -------------------------------- ### Extracting Configuration to Testable Functions Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md A better pattern for testing involves extracting configuration logic into separate functions. This allows for easier mocking of dependencies during tests. ```typescript // src/config.ts export function getApiUrl(): string { return import.meta.env.API_URL; } export function getApiClient() { return { baseUrl: getApiUrl(), timeout: parseInt(import.meta.env.API_TIMEOUT, 10), }; } // src/__tests__/config.test.ts import { describe, it, expect, vi } from 'vitest'; import * as config from '../config'; describe('Configuration', () => { it('should construct API client with environment values', () => { const client = config.getApiClient(); expect(client.baseUrl).toBeDefined(); expect(client.timeout).toBeGreaterThan(0); }); }); ``` -------------------------------- ### CLI Commands Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/README.md Vite Envs provides CLI commands for managing TypeScript type definitions and injecting environment variables at runtime. ```APIDOC ## CLI Commands ### Description These commands allow you to manage type definitions and inject environment variables using the Vite Envs CLI. ### Commands - **`npx vite-envs update-types`**: Updates the TypeScript type definitions for your environment variables. - **`npx vite-envs`**: Injects environment variables at runtime. This command typically runs as part of your build or deployment process. ``` -------------------------------- ### Set Execute Permissions for vite-envs.sh Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/errors.md Ensure the vite-envs.sh script has execute permissions. This is crucial for the script to run correctly during deployment. ```bash chmod +x vite-envs.sh ``` -------------------------------- ### Embed JSON Configuration in HTML Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Embed configuration as JSON directly into the HTML for frontend access. This pattern is useful for injecting runtime configurations. ```html
``` -------------------------------- ### Restart Development Server Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/errors.md If .env file changes are not reflected and hot reload is not functioning, restarting the development server can resolve the issue. ```bash npm run dev ``` -------------------------------- ### Shell Script Alternative for Injection Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/cli-commands.md This is a self-contained shell script that can be used instead of `npx vite-envs` for post-build injection, particularly in deployment scenarios where Node.js might not be available at runtime. ```bash ./vite-envs.sh ``` -------------------------------- ### Initialize vite-envs in Vite Config Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Add the viteEnvs plugin to your vite.config.ts. It must come before framework plugins like react(). ```typescript import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import { viteEnvs } from "vite-envs"; export default defineConfig({ plugins: [ viteEnvs(), // Must come before framework plugins react(), ], }); ``` -------------------------------- ### Kubernetes Deployment Stage in GitLab CI Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Sets up the deploy stage for a GitLab CI pipeline to update a Kubernetes deployment. It uses kubectl to set the new image for the application. ```yaml deploy: stage: deploy image: bitnami/kubectl:latest script: - kubectl set image deployment/myapp \ myapp=$CI_REGISTRY_IMAGE:$CI_COMMIT_SHA ``` -------------------------------- ### Runtime Environment Variable Injection for Docker Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Inject environment variables into Docker containers at runtime using the `-e` flag. This allows for flexible configuration of deployed applications. ```bash # Production deployment docker run \ -e API_URL="https://api.production.example.com" \ -e API_KEY="prod-key-xyz789" \ -e DATABASE_URL="postgresql://prod-user:pass@prod-host/proddb" \ -e DEBUG="false" \ myapp:latest # Staging deployment docker run \ -e API_URL="https://api.staging.example.com" \ -e API_KEY="staging-key-abc123" \ -e DATABASE_URL="postgresql://staging-user:pass@staging-host/stagingdb" \ -e DEBUG="true" \ myapp:latest ``` -------------------------------- ### Declare JSON Configuration in .env Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/usage-patterns.md Declare environment variables, including JSON strings, in the .env file for consistent configuration across environments. ```bash # .env CONFIG_JSON={"apiUrl":"","features":["auth","payments"],"version":"1.0.0"} ``` -------------------------------- ### Vite-Envs Build Configuration Data Structure Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/module-architecture.md Defines the structure of the .vite-envs.json file generated during the build process. It includes version, asset paths, environment variables from various sources, and the name for the global environment object. ```javascript { version: "4.7.1", // From package.json assetsUrlPath: "/assets", // From config htmlPre: "...", // Before EJS rendering declaredEnv: { API_URL: "", ... }, // From .env computedEnv: { BUILD_TIME: "...", ... }, // From computedEnv option baseBuildTimeEnv: { BASE_URL: "/", ... }, // From Vite config nameOfTheGlobal: "__VITE_ENVS" // From option } ``` -------------------------------- ### Generate Service Worker Environment JavaScript File Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/helper-functions.md Creates a JavaScript file (`swEnv.js`) in the distribution directory to make environment variables accessible within service workers. It handles base64 encoding and decoding for safe transfer. ```javascript // NOTE: This file is auto-generated by vite-envs. const envWithValuesInBase64 = { ... }; const env = {}; Object.keys(envWithValuesInBase64).forEach(function (name) { env[name] = JSON.parse( new TextDecoder().decode(...) ); }); self.__VITE_ENVS = env; ``` ```javascript // src/sw.ts (service worker file) // Import the generated environment file importScripts('swEnv.js'); // Access environment variables const apiUrl = self.__VITE_ENVS.API_URL; const debugMode = self.__VITE_ENVS.DEBUG_MODE; self.addEventListener('message', event => { // Can use environment variables here console.log(`API: ${apiUrl}`); }); ``` -------------------------------- ### Using EJS Expressions in index.html Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/api-reference/viteEnvs.md Demonstrates how to use EJS expressions with `import.meta.env` within your `index.html` when `indexAsEjs` is enabled in the viteEnvs plugin. ```html <%= import.meta.env.APP_NAME.toUpperCase() %> ``` -------------------------------- ### Helper Functions Source: https://github.com/garronej/vite-envs/blob/main/_autodocs/MANIFEST.md Reference for internal utility functions used within vite-envs, such as parsing .env files and decoding values. ```APIDOC ## Helper Functions ### `parseDotEnv()` #### Description Parses the content of .env files. ### `parseEnvValue()` #### Description Handles Base64 decoding for environment variable values. ### `getScriptThatDefinesTheGlobal()` #### Description Generates a script that defines the global variable for environment variables. ### `renderHtmlAsEjs()` #### Description Renders HTML content using EJS templating. ### `substituteHtmPlaceholders()` #### Description Substitutes placeholders within HTML content. ### `injectInHeadBeforeFirstScriptTag()` #### Description Injects content into the head of an HTML document before the first script tag. ### `createSwEnvJsFile()` #### Description Generates a JavaScript file for service worker environment variables. ```