react-spa-template/scripts/vite-plugin-app-config.js
2025-04-19 19:24:27 +02:00

99 lines
2.6 KiB
JavaScript

/**
* Vite plugin to inject app-config.js into the HTML head during development
*/
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { spawn } from "child_process";
// Get the directory name in ESM
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// Helper function for colorized logging like Vite
function formatLog(label, message, color = "\x1b[36m ") {
// Default to cyan color
const reset = "\x1b[0m";
const dim = "\x1b[2m";
const arrow = `${dim}${color}${reset}`;
const formattedLabel = `${color}${label}:${reset}`;
return ` ${arrow} ${formattedLabel} ${message}`;
}
/**
* Creates a Vite plugin that injects the app-config.js script into the HTML head
* @returns {import('vite').Plugin}
*/
function appConfigPlugin() {
return {
name: "vite-plugin-app-config",
configureServer(server) {
// Run the generate-app-config.js script when the dev server starts
const scriptPath = path.resolve(__dirname, "generate-app-config.js");
const generateConfig = () => {
const process = spawn("node", [scriptPath], {
stdio: "inherit",
shell: true,
});
process.on("error", (err) => {
console.error(
formatLog(
"Error",
`Failed to run generate-app-config.js: ${err}`,
"\x1b[31m ",
),
); // Red
});
};
// Generate config on server start
generateConfig();
// Watch for changes in .env files and regenerate app-config.js
const envFiles = [
".env",
".env.development",
".env.local",
".env.development.local",
];
envFiles.forEach((file) => {
const filePath = path.resolve(process.cwd(), file);
if (fs.existsSync(filePath)) {
server.watcher.add(filePath);
}
});
server.watcher.on("change", (file) => {
if (envFiles.some((envFile) => file.endsWith(envFile))) {
console.log(
formatLog(
"Changed",
`ENV file: ${path.basename(file)}`,
"\x1b[34m ",
),
); // Blue
generateConfig();
}
});
},
transformIndexHtml(html) {
// Check if the app-config.js script is already in the HTML
if (!html.includes("app-config.js")) {
// Insert the script tag after the opening head tag
return html.replace(
"<head>",
'<head>\n <script src="./app-config.js"></script>',
);
}
return html;
},
};
}
export default appConfigPlugin;