Skip to content

Commit 5c6b220

Browse files
authored
Convert environment variable generation script from bash to nodejs (#319)
* Convert environment variable generation script from bash to nodejs * Remember to Prettier always
1 parent de9db3e commit 5c6b220

File tree

4 files changed

+45
-35
lines changed

4 files changed

+45
-35
lines changed

Dockerfile

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,6 @@
22
# This image is around 50 megabytes
33
FROM node:18-alpine3.18 AS builder
44

5-
# Environment variable generation script needs bash
6-
RUN apk add --no-cache bash
7-
85
# Create app directory
96
WORKDIR /app
107

@@ -18,7 +15,7 @@ RUN npm ci --verbose
1815
RUN npm run build
1916

2017
# Create environment variable js file
21-
RUN chmod +x env.sh && ./env.sh
18+
RUN node generate-env-browser.js
2219

2320
### STAGE 2: Run ###
2421
# This image is around 5 megabytes

env.sh

Lines changed: 0 additions & 30 deletions
This file was deleted.

generate-env-browser.js

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import fs from "node:fs";
2+
import process from "node:process";
3+
4+
const JS_FILE = "env-config.js";
5+
const ENV_FILE = ".env";
6+
7+
// Remove existing config file
8+
if (fs.existsSync(JS_FILE)) {
9+
fs.unlinkSync(JS_FILE);
10+
}
11+
// Create new file
12+
fs.writeFileSync(JS_FILE, "", "utf-8");
13+
14+
// Add assignment
15+
fs.appendFileSync(JS_FILE, "window._env_ = {\n");
16+
17+
// Read each line in .env file
18+
// Each line represents key=value pairs
19+
const envFile = fs.readFileSync(ENV_FILE, "utf-8");
20+
const lines = envFile.split("\n");
21+
22+
lines.forEach((line) => {
23+
// Ignore comments, lines starting with hash
24+
if (line.startsWith("#")) {
25+
return;
26+
}
27+
// Split env variables by character `=`
28+
if (line.includes("=")) {
29+
const [varname, varvalue] = line.split("=");
30+
31+
// Read value of current variable if exists as Environment variable
32+
let value = process.env[varname] || varvalue;
33+
// Otherwise use value from .env file
34+
if (typeof value === "undefined") {
35+
value = varvalue;
36+
}
37+
38+
// Append configuration property to JS file
39+
fs.appendFileSync(JS_FILE, ` ${varname}: "${value}",\n`);
40+
}
41+
});
42+
43+
fs.appendFileSync(JS_FILE, "};");

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@
3939
"use-image": "^1.1.1"
4040
},
4141
"scripts": {
42-
"start": "chmod +x ./env.sh && sh ./env.sh && cp env-config.js ./public/ && vite",
42+
"start": "node generate-env-browser.js && cp env-config.js ./public/ && vite",
4343
"test": "jest",
4444
"build": "vite build",
4545
"lint": "eslint --ignore-path .gitignore . --ext .ts,.tsx,.jsx,.js",

0 commit comments

Comments
 (0)