@runtime-env/vite-plugin 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 Ernest
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,87 @@
1
+ # @runtime-env/vite-plugin
2
+
3
+ Zero-config Vite plugin for `runtime-env`.
4
+
5
+ ## Installation
6
+
7
+ ```sh
8
+ npm install --save-dev @runtime-env/vite-plugin
9
+ ```
10
+
11
+ ## Setup
12
+
13
+ Before using the plugin, ensure you have the following prerequisites in your project:
14
+
15
+ 1. **Define your environment schema**
16
+ Create a `.runtimeenvschema.json` file in your project root to define the structure and validation of your environment variables:
17
+ ```json
18
+ {
19
+ "type": "object",
20
+ "properties": {
21
+ "API_URL": { "type": "string" }
22
+ },
23
+ "required": ["API_URL"]
24
+ }
25
+ ```
26
+ 2. **Provide local environment variables**
27
+ Create a `.env` (or `.env.local`, `.env.development`, etc.) file to provide values for development:
28
+ ```env
29
+ API_URL=http://localhost:3000
30
+ ```
31
+ 3. **Load the runtime environment**
32
+ Add a `<script>` tag to your `index.html` **before** your main entry point to load the generated environment variables:
33
+ ```html
34
+ <script src="/runtime-env.js"></script>
35
+ ```
36
+ > [!IMPORTANT]
37
+ > In production, you are responsible for generating `/runtime-env.js` and (optionally) interpolating files at startup (e.g., in your Docker entrypoint) using the `@runtime-env/cli`.
38
+
39
+ ## Usage
40
+
41
+ Add the plugin to your `vite.config.ts`:
42
+
43
+ ```ts
44
+ import { defineConfig } from "vite";
45
+ import runtimeEnv from "@runtime-env/vite-plugin";
46
+
47
+ export default defineConfig({
48
+ plugins: [runtimeEnv()],
49
+ });
50
+ ```
51
+
52
+ ### Accessing Variables
53
+
54
+ **In JavaScript/TypeScript:**
55
+
56
+ ```ts
57
+ // Variables are available globally
58
+ const apiUrl = runtimeEnv.API_URL;
59
+ ```
60
+
61
+ **In `index.html` (Template Interpolation):**
62
+
63
+ ```html
64
+ <!-- Use lodash-style templates -->
65
+ <script src="https://maps.googleapis.com/maps/api/js?key=<%= runtimeEnv.GOOGLE_MAPS_API_KEY %>"></script>
66
+ ```
67
+
68
+ That's it! The plugin automatically handles the following:
69
+
70
+ - **Development**: Dynamically serves `/runtime-env.js` and watches for changes in `.env` files or your schema.
71
+ - **Build**: Only runs `gen-ts` to ensure your type definitions are up-to-date. It **does not** generate `runtime-env.js` or interpolate `index.html`, ensuring your build artifacts remain generic and environment-agnostic.
72
+ - **Preview**: Hooks into the Vite preview server to generate `/runtime-env.js` and perform HTML interpolation on the fly, allowing you to test your production build locally.
73
+ - **Testing (Vitest)**: Automatically generates a temporary `runtime-env.js` and injects it into Vitest's `setupFiles`, providing `globalThis.runtimeEnv` during your tests.
74
+
75
+ ## Why runtime-env?
76
+
77
+ Vite's built-in `import.meta.env` is **build-time**. This means environment variables are "baked into" your JavaScript bundles during the build process, requiring a full rebuild for every environment (e.g., staging, production, or per-customer deployments).
78
+
79
+ `@runtime-env` enables the **"Build once, deploy anywhere"** philosophy. By loading environment variables from a separate `/runtime-env.js` file at runtime, you can:
80
+
81
+ - Use the **exact same Docker image** or build artifact across all environments.
82
+ - Update configuration in seconds without a CI/CD rebuild.
83
+ - Ensure strict validation of environment variables via JSON Schema.
84
+
85
+ ## Advanced Usage
86
+
87
+ For more details on the underlying mechanics and CLI options, refer to the [main documentation](https://github.com/runtime-env/runtime-env#runtime-env).
@@ -0,0 +1,2 @@
1
+ import type { Plugin } from "vite";
2
+ export declare function buildPlugin(): Plugin;
package/dist/build.js ADDED
@@ -0,0 +1,13 @@
1
+ import { isTypeScriptProject, runRuntimeEnvCommand } from "./utils.js";
2
+ export function buildPlugin() {
3
+ return {
4
+ name: "runtime-env-build",
5
+ config(config, configEnv) {
6
+ if (configEnv.command === "build") {
7
+ if (isTypeScriptProject(config.root || process.cwd())) {
8
+ runRuntimeEnvCommand("gen-ts", "src/runtime-env.d.ts");
9
+ }
10
+ }
11
+ },
12
+ };
13
+ }
package/dist/dev.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import type { Plugin } from "vite";
2
+ export declare function devPlugin(): Plugin;
package/dist/dev.js ADDED
@@ -0,0 +1,63 @@
1
+ import { resolve } from "path";
2
+ import { writeFileSync, readFileSync, rmSync, existsSync } from "fs";
3
+ import { isTypeScriptProject, runRuntimeEnvCommand, getTempDir, getViteEnvFiles, } from "./utils.js";
4
+ const schemaFile = ".runtimeenvschema.json";
5
+ export function devPlugin() {
6
+ return {
7
+ name: "runtime-env-dev",
8
+ configureServer(server) {
9
+ if (server.config.mode === "test")
10
+ return;
11
+ const envDir = server.config.envDir || server.config.root;
12
+ const envFiles = getViteEnvFiles(server.config.mode, envDir);
13
+ const watchFiles = [schemaFile, ...envFiles];
14
+ function run() {
15
+ const devOutputDir = getTempDir("dev");
16
+ const devOutputPath = resolve(devOutputDir, "runtime-env.js");
17
+ runRuntimeEnvCommand("gen-js", devOutputPath, envFiles);
18
+ if (isTypeScriptProject(server.config.root)) {
19
+ runRuntimeEnvCommand("gen-ts", "src/runtime-env.d.ts");
20
+ }
21
+ }
22
+ run();
23
+ server.middlewares.use((req, res, next) => {
24
+ const base = server.config.base || "/";
25
+ const path = req.url?.split("?")[0];
26
+ const targetPath = (base + "/runtime-env.js").replace(/\/+/g, "/");
27
+ if (path === targetPath) {
28
+ const devOutputDir = getTempDir("dev");
29
+ const devOutputPath = resolve(devOutputDir, "runtime-env.js");
30
+ if (existsSync(devOutputPath)) {
31
+ res.setHeader("Content-Type", "application/javascript");
32
+ res.end(readFileSync(devOutputPath, "utf8"));
33
+ return;
34
+ }
35
+ }
36
+ next();
37
+ });
38
+ server.watcher.add(watchFiles);
39
+ server.watcher.on("change", (file) => {
40
+ if (watchFiles.includes(file)) {
41
+ run();
42
+ }
43
+ });
44
+ },
45
+ transformIndexHtml(html, ctx) {
46
+ if (ctx.server && ctx.server.config.command === "serve") {
47
+ const envDir = ctx.server.config.envDir || ctx.server.config.root;
48
+ const envFiles = getViteEnvFiles(ctx.server.config.mode, envDir);
49
+ const tmpDir = getTempDir("dev-interpolate");
50
+ try {
51
+ const htmlFile = resolve(tmpDir, "index.html");
52
+ writeFileSync(htmlFile, html, "utf8");
53
+ runRuntimeEnvCommand("interpolate", htmlFile, envFiles, htmlFile);
54
+ html = readFileSync(htmlFile, "utf8");
55
+ return html;
56
+ }
57
+ finally {
58
+ rmSync(tmpDir, { recursive: true, force: true });
59
+ }
60
+ }
61
+ },
62
+ };
63
+ }
@@ -0,0 +1,2 @@
1
+ import type { Plugin } from "vite";
2
+ export default function runtimeEnv(): Plugin[];
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ import { devPlugin } from "./dev.js";
2
+ import { buildPlugin } from "./build.js";
3
+ import { previewPlugin } from "./preview.js";
4
+ import { vitestPlugin } from "./vitest.js";
5
+ export default function runtimeEnv() {
6
+ return [devPlugin(), buildPlugin(), previewPlugin(), vitestPlugin()];
7
+ }
@@ -0,0 +1,2 @@
1
+ import type { Plugin } from "vite";
2
+ export declare function previewPlugin(): Plugin;
@@ -0,0 +1,64 @@
1
+ import { resolve } from "path";
2
+ import { readFileSync, writeFileSync, existsSync, rmSync } from "fs";
3
+ import { runRuntimeEnvCommand, getTempDir, getViteEnvFiles } from "./utils.js";
4
+ export function previewPlugin() {
5
+ return {
6
+ name: "runtime-env-preview",
7
+ configurePreviewServer(server) {
8
+ server.middlewares.use((req, res, next) => {
9
+ const base = server.config.base || "/";
10
+ const url = req.url?.split("?")[0] || "";
11
+ // Normalize path to be relative to base
12
+ let path = url;
13
+ if (url.startsWith(base)) {
14
+ path = url.slice(base.length);
15
+ }
16
+ if (!path.startsWith("/")) {
17
+ path = "/" + path;
18
+ }
19
+ path = path.replace(/\/+/g, "/");
20
+ const envDir = server.config.envDir || server.config.root;
21
+ const envFiles = getViteEnvFiles(server.config.mode, envDir);
22
+ // Serve runtime-env.js
23
+ if (path === "/runtime-env.js") {
24
+ const tmpDir = getTempDir("preview-gen-js");
25
+ const tmpPath = resolve(tmpDir, "runtime-env.js");
26
+ try {
27
+ runRuntimeEnvCommand("gen-js", tmpPath, envFiles);
28
+ if (existsSync(tmpPath)) {
29
+ const content = readFileSync(tmpPath, "utf8");
30
+ res.setHeader("Content-Type", "application/javascript");
31
+ res.end(content);
32
+ return;
33
+ }
34
+ }
35
+ finally {
36
+ rmSync(tmpDir, { recursive: true, force: true });
37
+ }
38
+ }
39
+ // Intercept index.html
40
+ if (path === "/" || path === "/index.html") {
41
+ const outDir = server.config.build.outDir || "dist";
42
+ const distIndexHtml = resolve(server.config.root, outDir, "index.html");
43
+ if (existsSync(distIndexHtml)) {
44
+ const tmpDir = getTempDir("preview-interpolate");
45
+ try {
46
+ const tmpHtmlPath = resolve(tmpDir, "index.html");
47
+ const originalHtml = readFileSync(distIndexHtml, "utf8");
48
+ writeFileSync(tmpHtmlPath, originalHtml, "utf8");
49
+ runRuntimeEnvCommand("interpolate", tmpHtmlPath, envFiles, tmpHtmlPath);
50
+ const interpolatedHtml = readFileSync(tmpHtmlPath, "utf8");
51
+ res.setHeader("Content-Type", "text/html");
52
+ res.end(interpolatedHtml);
53
+ return;
54
+ }
55
+ finally {
56
+ rmSync(tmpDir, { recursive: true, force: true });
57
+ }
58
+ }
59
+ }
60
+ next();
61
+ });
62
+ },
63
+ };
64
+ }
@@ -0,0 +1,5 @@
1
+ export declare function isTypeScriptProject(root: string): boolean;
2
+ export declare function getViteEnvFiles(mode: string, envDir: string): string[];
3
+ export declare function getRuntimeEnvCommandLineArgs(command: string, outputFile: string, envFiles?: string[], inputFile?: string): string[];
4
+ export declare function runRuntimeEnvCommand(command: string, outputFile: string, envFiles?: string[], inputFile?: string): void;
5
+ export declare function getTempDir(subDir: string): string;
package/dist/utils.js ADDED
@@ -0,0 +1,55 @@
1
+ import { existsSync, mkdirSync } from "fs";
2
+ import { resolve } from "path";
3
+ import { spawnSync } from "child_process";
4
+ import { createRequire } from "module";
5
+ const require = createRequire(import.meta.url);
6
+ const schemaFile = ".runtimeenvschema.json";
7
+ const globalVariableName = "runtimeEnv";
8
+ export function isTypeScriptProject(root) {
9
+ return existsSync(resolve(root, "tsconfig.json"));
10
+ }
11
+ export function getViteEnvFiles(mode, envDir) {
12
+ const envFiles = [".env", ".env.local", `.env.${mode}`, `.env.${mode}.local`];
13
+ return envFiles
14
+ .map((file) => resolve(envDir, file))
15
+ .filter((file) => existsSync(file));
16
+ }
17
+ export function getRuntimeEnvCommandLineArgs(command, outputFile, envFiles = [], inputFile) {
18
+ let args = [
19
+ "--schema-file",
20
+ schemaFile,
21
+ "--global-variable-name",
22
+ globalVariableName,
23
+ command,
24
+ ];
25
+ if (command === "gen-ts") {
26
+ args.push("--output-file", outputFile);
27
+ }
28
+ else if (command === "gen-js") {
29
+ args.push(...envFiles.map((file) => ["--env-file", file]).flat());
30
+ args.push("--output-file", outputFile);
31
+ }
32
+ else if (command === "interpolate" && inputFile) {
33
+ args.push(...envFiles.map((file) => ["--env-file", file]).flat());
34
+ args.push("--input-file", inputFile, "--output-file", outputFile);
35
+ }
36
+ return args;
37
+ }
38
+ export function runRuntimeEnvCommand(command, outputFile, envFiles = [], inputFile) {
39
+ const args = getRuntimeEnvCommandLineArgs(command, outputFile, envFiles, inputFile);
40
+ let cliPath;
41
+ try {
42
+ cliPath = require.resolve("@runtime-env/cli/bin/runtime-env.js");
43
+ }
44
+ catch (e) {
45
+ // Fallback to local node_modules/.bin if require.resolve fails (e.g. during development or in some monorepo setups)
46
+ cliPath = resolve("node_modules", ".bin", "runtime-env");
47
+ }
48
+ spawnSync("node", [cliPath, ...args]);
49
+ }
50
+ export function getTempDir(subDir) {
51
+ const root = process.cwd();
52
+ const tempDir = resolve(root, "node_modules", ".runtime-env", subDir);
53
+ mkdirSync(tempDir, { recursive: true });
54
+ return tempDir;
55
+ }
@@ -0,0 +1,2 @@
1
+ import type { Plugin } from "vite";
2
+ export declare function vitestPlugin(): Plugin;
package/dist/vitest.js ADDED
@@ -0,0 +1,39 @@
1
+ import { resolve } from "path";
2
+ import { rmSync } from "fs";
3
+ import { isTypeScriptProject, runRuntimeEnvCommand, getTempDir, getViteEnvFiles, } from "./utils.js";
4
+ export function vitestPlugin() {
5
+ return {
6
+ name: "runtime-env-vitest",
7
+ config(config, configEnv) {
8
+ if (config.mode === "test") {
9
+ const root = config.root || process.cwd();
10
+ // Generate runtime-env.d.ts for Vitest type checking
11
+ if (isTypeScriptProject(root)) {
12
+ runRuntimeEnvCommand("gen-ts", "src/runtime-env.d.ts");
13
+ }
14
+ const envDir = config.envDir || root;
15
+ const envFiles = getViteEnvFiles(config.mode, envDir);
16
+ // Generate runtime-env.js for Vitest runtime access
17
+ const vitestOutputDir = getTempDir("vitest");
18
+ const vitestOutputPath = resolve(vitestOutputDir, "runtime-env.js");
19
+ // Ensure directory is clean
20
+ rmSync(vitestOutputDir, { recursive: true, force: true });
21
+ getTempDir("vitest"); // Re-create it clean
22
+ runRuntimeEnvCommand("gen-js", vitestOutputPath, envFiles);
23
+ // Automatically inject setupFiles for Vitest
24
+ const vitestConfig = config.test || {};
25
+ const setupFiles = vitestConfig.setupFiles || [];
26
+ if (Array.isArray(setupFiles)) {
27
+ setupFiles.push(vitestOutputPath);
28
+ }
29
+ else {
30
+ vitestConfig.setupFiles = [setupFiles, vitestOutputPath];
31
+ }
32
+ config.test = {
33
+ ...vitestConfig,
34
+ setupFiles,
35
+ };
36
+ }
37
+ },
38
+ };
39
+ }
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@runtime-env/vite-plugin",
3
+ "version": "0.0.0",
4
+ "description": "Opinionated Vite plugin for runtime-env",
5
+ "license": "MIT",
6
+ "author": "Ernest",
7
+ "keywords": [
8
+ "vite",
9
+ "plugin",
10
+ "runtime-env"
11
+ ],
12
+ "main": "dist/index.js",
13
+ "types": "dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "import": "./dist/index.js",
17
+ "require": "./dist/index.js",
18
+ "types": "./dist/index.d.ts"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "scripts": {
25
+ "build": "rimraf dist && tsc",
26
+ "pack": "npm pack && node ../../scripts/rename-tgz.js"
27
+ },
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "git+https://github.com/runtime-env/runtime-env.git",
31
+ "directory": "packages/vite-plugin"
32
+ },
33
+ "bugs": {
34
+ "url": "https://github.com/runtime-env/runtime-env/issues"
35
+ },
36
+ "homepage": "https://github.com/runtime-env/runtime-env#readme",
37
+ "dependencies": {
38
+ "@runtime-env/cli": "^0.7.8"
39
+ },
40
+ "devDependencies": {
41
+ "vite": "7.3.0"
42
+ },
43
+ "type": "module"
44
+ }