vite-plugin-runtime-env
Version:
Vite plugin which enables you to configure your environment variables when deploying your app.
136 lines (134 loc) • 4.52 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
default: () => runtimeEnv
});
module.exports = __toCommonJS(src_exports);
var import_magic_string = __toESM(require("magic-string"), 1);
var viteInternalEnvs = ["MODE", "BASE_URL", "PROD", "DEV", "SSR"];
function createNameFilter(envPrefix, ignoreEnv) {
const hasPrefix = (name) => {
if (typeof envPrefix === "string") {
return name.startsWith(envPrefix);
}
return envPrefix.some((prefix) => name.startsWith(prefix));
};
const shouldBeIgnored = (name) => {
if (viteInternalEnvs.includes(name)) {
return true;
}
if (!ignoreEnv) {
return false;
}
if (typeof ignoreEnv === "function") {
return ignoreEnv(name);
}
return ignoreEnv.includes(name);
};
return (name) => hasPrefix(name) && !shouldBeIgnored(name);
}
function createVariableDecorator(substitutionSyntax = "dollar-curly") {
return (name) => {
switch (substitutionSyntax) {
case "dollar-basic":
return `$${name}`;
case "handlebars":
return `{{${name}}}`;
case "dollar-curly":
default:
return `\${${name}}`;
}
};
}
function runtimeEnv(options = {}) {
const matches = /* @__PURE__ */ new Set();
let envPrefix = "VITE_";
let needSourceMap = false;
let isDevServer = false;
const {
variableName = "window.env",
injectHtml = true
} = options;
const shouldReplaceName = createNameFilter(envPrefix, options.ignoreEnv);
const wrapVariable = createVariableDecorator(options.substitutionSyntax);
return {
name: "runtime-env",
configResolved: (resolvedConfig) => {
if (resolvedConfig.envPrefix) {
envPrefix = resolvedConfig.envPrefix;
}
if (resolvedConfig.build.sourcemap) {
needSourceMap = true;
}
if (resolvedConfig.command === "serve") {
isDevServer = true;
}
},
transform: (code) => {
if (isDevServer) {
return null;
}
const magicString = new import_magic_string.default(code);
const importMetaPattern = /import\.meta\.env\.([A-Z0-9_]+)/g;
let match;
while (match = importMetaPattern.exec(code)) {
const start = match.index;
const end = start + match[0].length;
const name = match[1];
if (shouldReplaceName(name)) {
magicString.overwrite(start, end, `${variableName}.${name}`);
matches.add(name);
}
}
if (!magicString.hasChanged()) {
return null;
}
if (!needSourceMap) {
return magicString.toString();
}
return {
code: magicString.toString(),
map: magicString.generateMap({ hires: true })
};
},
transformIndexHtml: () => {
if (isDevServer || !injectHtml || matches.size === 0) {
return void 0;
}
const vars = [...matches.values()].map((name) => `"${name}":"${wrapVariable(name)}"`).join(",");
return [{
tag: "script",
attrs: { type: "application/javascript" },
children: `${variableName}=JSON.parse('{${vars}}');`
}];
}
};
}