Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to provide runtime environment variables for Single Page App

2025-01-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

It is believed that many inexperienced people have no idea about how to provide runtime environment variables for Single Page App. Therefore, this article summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.

Recently conquered a pain point of previously deployed single-page-app: support for runtime environment variables. Here's a look at the problem and the current solution.

SPA has no pain points for runtime environment variables

At present, most of my projects are developed in a separate way. The front end is basically the standard react spa application created by create-react-app. In deployment, this kind of spa is to package all js and css into one or more files and then use serve or other similar http server to provide services in the form of static files, but this front-end static file conversation application does not have the support of nodejs, so it is impossible to use runtime injection of environment variables such as process.env.

At present, create-react-app provides a solution for compiling runtime environment variables, because it is supported by nodejs when build, and environment variables are injected when compiling spa through the way of REACT_APP_API_URL= http://xxx.com yarn run build. So can compile-time environment variables solve the problem? It depends. You can make a simple comparison.

To know what kind of environment variables we usually inject into spa. Well, my needs here are limited, and in order for the front and rear ends to work together, the environment variables I need are the entrances to the back-end API. For cases where the deployment process is simple and the production environment is fixed (especially the back-end production environment IP and domain name is fixed), you can simply write and inject the entry of the backend directly at compile time. However, if there are multiple environments (staging) requirements are not applicable, if there is no run-time environment variable support for different environments to provide different entries can only recompile the application and inject different variables.

There is no need to modify our environment variables while the application is running. It is obvious that the runtime environment variable supports the ability to modify the environment variable through restart, and if there is this flexibility to modify the environment variable, the compile-time environment variable obviously cannot be satisfied.

Select and tailor the code at compile time. Obviously, this is the best place to use compile-time environment variables.

To put it bluntly, the role of environmental variables in different periods is different. It is impossible for the two to replace each other, and it is not convenient to use compile-time environment variables in both scenarios where runtime environment variables are more comfortable. Let's take a look at the current method of getting spa applications to support runtime environment variables, and here we will take the template of create-react-app as an example.

Global configuration + Docker deployment

There is no such thing as process.env at the front end, so we can only simulate it with the global variables of javascript. When running the packaged spa, we need to use the shell script to generate the config.js file and have it translate the necessary environment variables into global variables. Then let the default entry html file introduce this global variable file.

First, we need a shell script that translates the environment variables into a config.js file:

#! / bin/bashif [[$CONFIG_VARS]]; then SPLIT=$ (echo $CONFIG_VARS | tr ","\ n ") ARGS= for VAR in ${SPLIT}; do ARGS=" ${ARGS}-v ${VAR} "done JSON= `json _ env-- json $ARGS`echo" = > Writing ${CONFIG_FILE_PATH} / config.js with ${JSON} "echo" window.__env = ${JSON} "> ${CONFIG_FILE_PATH} / config.jsfiexec" $@ "

If we provide such an environment variable,

Export REACT_APP_API_PREFIX= http://petstore-backend.example.comexport CONFIG_VARS=REACT_APP_API_PREFIX

Then the generated config.js file looks like this:

Window.__env = {'REACT_APP_API_PREFIX':' http://petstore-backend.example.com'}

Then, we need to introduce the config.js file we generated into the original index.html template file:

... You need to enable JavaScript to run this app.

In this way, we have a global object for window.__env that contains all the runtime environment variables. We can use it in the following ways:

Axios.defaults.adapter = httpAdapter;let baseUrl;let env = window.__env | | {}; / 1if (process.env.NODE_ENV = 'test') {baseUrl =' http://example.com';} else if (process.env.NODE_ENV = 'development') {baseUrl = env.REACT_APP_API_PREFIX | |' http://localhost:8080'; / / 2} else {baseUrl = env.REACT_APP_API_PREFIX } const fetcher = axios.create ({baseURL: baseUrl, headers: {'Content-Type':' application/json'}})

Directly introduce the window.__env global variable into the file

Just reference the variables where you need them.

Of course, this solution that relies on shell to generate config.js will not be used until we have packaged the spa. In order to make better use of this shell, we can use docker to solidify its startup process in the application startup process in the way of entrypoint. SocialEngine/docker-nginx-spa implements this scheme, which is a good way to use base image. If we need to create a create-react-app spa that supports runtime environment variables, first follow the steps above to modify the public/index.html and use window.__env as the environment variable. Then provide a Dockerfile that inherits from SocialEngine/docker-nginx-spa.

FROM socialengine/nginx-spaCOPY build/ / app

Where build/ is the default directory where create-react-app compiles to generate static files. The way to package and run the application is as follows:

$yarn run build$ docker build-t spa-app. $docker run-e CONFIG_VARS=REACT_APP_API_PREFIX-e REACT_APP_API_PREFIX= http://petstore-backend.example.com-p 3000 docker run 80 spa-app

Of course, our local development environment doesn't have to be so troublesome. Just create your own config.js in the public/ directory and plug in the environment variables you need for your development. After docker, the command triggered by entrypoint automatically overwrites the config.js file.

Here is a sample project.

After reading the above, have you learned how to provide runtime environment variables for Single Page App? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report