For the project built by react scaffolding, how to automatically match the host address of the back-end interface between the production environment and the online test environment when requesting the back-end interface?

problem description

for the project built by react scaffolding,
when requesting the backend interface, url = host/ API name
each time you switch between the production environment and the online test environment (you need to change the code to upgrade the version of the back-end interface between the test environment and the formal online environment), you need to manually modify the address of the backend interface host.
now you want the production environment and the online test environment to automatically identify the host address. How to configure it?
because all online users execute the npm run build command.

Apr.07,2021

write a runtime


inject configuration information into html according to different environments

window.__config = {
    host: ''
};


const host = window.__config.host;
request(`${host}/api`);

define a constant through DefinePlugin in webpack .
then assign the constant via process.env.NODE_ENV .
webpack.config.js

const url = `${requestHost}/api`;
fetch(url);
Menu