Skip to content

Possible improvement on Docker support #111

@lextm

Description

@lextm

Currently the steps documented for Docker support do not quite match real world setup,

  • It's not quite common to use a Node image for production deployment.
  • yarn start clearly is using the debug build.

To support a commonly used base image such as nginx, which does not have Node installed, the challenge is how to generate __ENV.js on the fly without Node.

I attached a shell script below that works in a similar way,

#!/bin/sh

# react-env.sh

scriptname="./__ENV.js"
sourcename="$1"

if [ -z "$sourcename" ]; then
  current=$(eval "echo \"\$ENVIRONMENT\"")
  if [ -z "$current" ]; then
    sourcename=".env"
  else
    sourcename=".env.$current"
  fi
fi

# Recreate config file
rm -rf "$scriptname"
touch "$scriptname"

# Add assignment 
echo "window.__ENV = {" >> "$scriptname"

# Read each line in .env file
# Each line represents key=value pairs
while read -r line || [ -n "$line" ];
do
  if printf '%s\n' "$line" | grep -q -e '^#.*'; then
    continue
  fi

  [ -z "$line" ] && continue

  # Split env variables by character `=`
  if printf '%s\n' "$line" | grep -q -e '='; then
    varname=$(printf '%s\n' "$line" | sed -e 's/=.*//')
    varvalue=$(printf '%s\n' "$line" | sed -e 's/^[^=]*=//')
  fi

  # Read value of current variable if exists as Environment variable
  env=$(eval "echo \"\$$varname\"")
  value=$(printf '%s\n' "$env")
  # Otherwise use value from .env file
  [ -z "$value" ] && value=${varvalue}
  
  # Append configuration property to JS file
  echo "  $varname: \"$value\"," >> "$scriptname"
done < "$sourcename"

echo "}" >> "$scriptname"

It is written in POSIX sh syntax, as many base images don't have bash.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions