How to pass environment variables to a frontend web application?

后端 未结 5 1305
攒了一身酷
攒了一身酷 2020-12-07 16:15

I am trying to containerize a frontend web application and I am having troubles to figure out how to pass environment variables. The application is a Angular application, so

5条回答
  •  旧时难觅i
    2020-12-07 16:29

    Put your environment variables in the index.html!!

    Trust me, I know where you are coming from! Baking environment-specific variables into the build phase of my Angular app goes against everything I have learned about portability and separation of concerns.

    But wait! Take a close look at a common Angular index.html:

    
    
    
      
      mysite
      
      
      
      
      
    
    
      
      
      
      
    
    
    

    This is all configuration!!!

    It is just like the docker-compose.yml that you are using to maintain your Docker apps:

    • versioned immutable assets
    • environment variables
    • application binding
    • environment meta-data
    • even the different bundles feel like layers of an docker image sorta, don't they?
      • runtime is like your base image that you rarely change.
      • polyfills are those things you need that didn't come included in the base image that you need.
      • main is your actual app that pretty much changes every release.

    You can do the same thing with your frontend app that you do with your Docker app!

    1. Build, version, and publish immutable assets (js bundles / Docker image)
    2. Publish a deployment manifest to staging (index.html / docker-compose.yml)
    3. Test in staging
    4. Publish a deployment manifest to production.. referencing the same assets you just tested! Instantly! Atomically!

    How??

    Just point the stinking /src/environments/environment.prod.ts at the window object.

    export const environment = (window as any).env;
    // or be a rebel and just use window.env directly in your components
    

    and add a script to your index.html with the environment variable WHERE THEY BELONG!:

    
    

    I feel so strongly about this approach I created a website dedicated to it: https://immutablewebapps.org. I think you will find there are a lot of other benefits!

    ~~~

    Now, I have done this successfully using two AWS S3 Buckets: one for the versioned static assets and one for just the index.html (it makes routing super simple: serve index.html for every path). I haven't done it running containers like you are proposing. If I were to use containers, I would want to make a clean separation between the building and publishing new assets, and releasing of a new index.html. Maybe I would render index.html on-the-fly from a template with the container's environment variables.

    If you choose this approach, I'd love to know how it turns out!

提交回复
热议问题