Skip to content

Commit

Permalink
Merge pull request #20 from garronej/service_worker
Browse files Browse the repository at this point in the history
Service worker
  • Loading branch information
garronej authored Apr 17, 2024
2 parents d440dfc + 1c1e01d commit 00c3600
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "vite-envs",
"version": "4.0.16",
"version": "4.1.0-rc.0",
"description": "Env var in Vite at container startup",
"repository": {
"type": "git",
Expand Down
45 changes: 45 additions & 0 deletions src/vite-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -583,6 +583,36 @@ export function viteEnvs(params?: {
});

fs.writeFileSync(indexHtmlFilePath, Buffer.from(processedHtml, "utf8"));

{
const envWithValuesInBase64 = Object.fromEntries(
Object.entries(mergedEnv).map(([key, value]) => [
key,
Buffer.from(`${value}`, "utf8").toString("base64")
])
);

const swEnv = [
`const envWithValuesInBase64 = ${JSON.stringify(
envWithValuesInBase64,
null,
2
)
.replace(/^"/, "")
.replace(/"$/, "")};`,
`const env = {};`,
`Object.keys(envWithValuesInBase64).forEach(function (name) {`,
` env[name] = new TextDecoder().decode(`,
` Uint8Array.from(`,
` atob(envWithValuesInBase64[name]),`,
` c => c.charCodeAt(0))`,
` );`,
`});`,
`self.${nameOfTheGlobal} = env;`
].join("\n");

fs.writeFileSync(pathJoin(distDirPath, "swEnv.js"), Buffer.from(swEnv, "utf8"));
}
})(processedHtml);

const placeholderForViteEnvsScript = `<!-- vite-envs script placeholder xKsPmLs30swKsdIsVx -->`;
Expand Down Expand Up @@ -693,6 +723,21 @@ export function viteEnvs(params?: {
`DIR=$(cd "$(dirname "$0")" && pwd)`,
``,
`echo "$processedHtml" > "$DIR/index.html"`,
``,
`swEnv_script="`,
`const envWithValuesInBase64 = $json;`,
`const env = {};`,
`Object.keys(envWithValuesInBase64).forEach(function (name) {`,
` env[name] = new TextDecoder().decode(`,
` Uint8Array.from(`,
` atob(envWithValuesInBase64[name]),`,
` c => c.charCodeAt(0))`,
` ).slice(0,-1);`,
`});`,
`self.${nameOfTheGlobal} = env;`,
`"`,
``,
`echo "$swEnv_script" > "$DIR/swEnv.js"`,
``
].join("\n");

Expand Down

0 comments on commit 00c3600

Please sign in to comment.