bersling
bersling

Reputation: 19312

How can I avoid building each environment separately in Angular?

So we currently have the following env files:

environment.dev.ts
environment.staging.ts
environment.prod.ts
environment.ts

What we do on the CI server is we build them all, except for the local one:

npm run buildDev && npm run buildStaging && npm run buildProd

However, this leads to long build times and it's basically redundant, since they all have the flag production: true, and the only differences are things like apiUrl: dev-api.example.com vs apiUrl: prod-api.example.com.

Is there some way to build those envs simultaneously and Angular checks if it can optimize the build speed by building it just once and then copying over the different envs at the end or similar?

Upvotes: 0

Views: 364

Answers (1)

Fred
Fred

Reputation: 21

If you are using docker for deploying you can do like that.

  1. In your static file index.html, reference a env-config.js file
<!DOCTYPE html>
<html lang="en">
  <head>    
    <title>App</title>
    <script src="env-config.js"></script>
  </head>
  <body>
    ...
  </body>
</html>
  1. In your docker file, reference an entrypoint file :
FROM nginx:1.15.2-alpine

# Nginx config
RUN rm -rf /etc/nginx/conf.d

# Static build
COPY build /usr/share/nginx/html/

# Default port exposure
EXPOSE 3000

# Copy .env file and shell script to container
WORKDIR /usr/share/nginx/html
COPY entrypoint.sh /

# Make our shell script executable
RUN chmod +x /entrypoint.sh

# Start Nginx server
ENTRYPOINT [ "/entrypoint.sh" ]
  1. Create an entrypoint file, which create the env-config.js file :
#!/bin/sh

# Recreate config file
rm -rf env-config.js
touch env-config.js

# Add assignment
echo "window._env_ = {" >> env-config.js

echo "APP_NAME: \"$APP_NAME\"," >> env-config.js
echo "APP_API_URL: \"$APP_API_URL\"," >> env-config.js

echo "}" >> env-config.js

echo "Starting Nginx"

nginx -g 'daemon off;'

  1. In your docker compose reference a env.list file :
version: '3.7'

services:
  app:
    image: com.web.app/app:latest
    env_file:
      - app/env.list
    ports:
      - 3000:3000
  1. Finally, in this env.list file, set up your variable for the desired environment:
APP_NAME=app
APP_API_URL=https://192.168.1.22:3000/app/api

Like that, you build one time with placeholder, and you deleguate to docker, about environment.

Upvotes: 1

Related Questions