I would like to inject the environment variable at run time by using env.sh script file to replace the env value. But I receive “Uncaught SyntaxError: Invalid or unexpected token” when I open my webpage.
I try to use # find /app/build -type f -exec sed -i “s|${key}|‘${value}’|g” ‘{}’ +
once I add single quote to value, it is worked to pass value to my react application but the value will contains the single quote. And I have to remove them by using
const API_BASE_URL = (process.env.REACT_APP_API_BASE_URL || “”).replace(
/'/g,
“”
);
I think this is not a proper solution, do anyone knows why it happened and how to solve it?
my env file :
REACT_APP_FEATURE_ENABLED=true
REACT_APP_API_BASE_URL=REACT_APP_API_BASE_URL
REACT_APP_SCOPE=REACT_APP_SCOPE
REACT_APP_CLIENT_ID=REACT_APP_CLIENT_ID
REACT_APP_TENANT_ID=REACT_APP_TENANT_ID
my docker file:
Stage 1: Build the React application
FROM node:18-alpine AS builder
Set the working directory inside the container
WORKDIR /app
Copy package.json and package-lock.json
COPY package*.json ./
Install dependencies
RUN npm install
Copy the rest of your application files
COPY . .
Build the React application
RUN npm run build
Stage 2: Serve the built files using a simple HTTP server
FROM node:18-alpine
Install a simple HTTP server to serve the built files
RUN npm install -g serve
Copy the build output from the builder stage
COPY --from=builder /app/build /app/build
Copy the entrypoint script
COPY env.sh /docker-entrypoint.d/env.sh
Ensure the script has execution permissions
RUN chmod +x /docker-entrypoint.d/env.sh
Expose the port your app runs on
EXPOSE 80
Define the entrypoint and command to run your app
ENTRYPOINT [“/docker-entrypoint.d/env.sh”]
CMD [“serve”, “-s”, “/app/build”, “-l”, “80”]
my env.sh file
#!/bin/sh
echo “Starting env.sh script”
Print all environment variables for debugging
echo “Environment variables:”
env
Replace placeholders in the built files with environment variables
for i in $(env | grep REACT_APP_)
do
key=$(echo $i | cut -d ‘=’ -f 1)
value=$(echo $i | cut -d ‘=’ -f 2-)
echo “Replacing ${key} with ${value}”
Replace placeholders in all files
find /app/build -type f -exec sed -i “s|${key}|${value}|g” ‘{}’ +
find /app/build -type f -exec sed -i “s|${key}|‘${value}’|g” ‘{}’ +
work with adding single quote, but the value I get also with single quote
done
echo “Environment variables replaced”
exec “$@”