在REACTJs项目中为qa、dev和prod使用多个web.config文件



我需要根据环境(dev、qa和prod(为我的应用程序设置一些头。有没有办法拥有多个web.config文件?或者我们可以访问web.config中的ENV变量吗?

PD:我的应用程序托管在azure 中

有多种方法可以实现

选项1:

利用过程环境:

在package.json中,更新您的脚本,使每个构建都有一个脚本

"build:dev": "cross-env ENVIRONMENT=development node parseEnv --exec:"react-scripts build"",
"build:prod": "cross-env ENVIRONMENT=production node parseEnv --exec:"react-scripts build"",
"build:qa": "cross-env ENVIRONMENT=qa node parseEnv --exec:"react-scripts build"",

您可以看到,我们正在脚本中传递ENVIRONMENT=

现在在根的同一级别创建一个parseEnv.js文件

parseEnv.js:

const dotenv = require('dotenv');
const fs = require('fs'); // to check if the file exists
const path = require('path'); // to get the current path
const { execSync } = require("child_process");
const currentPath = path.join(__dirname);
// Create the fallback path (the production .env)
const basePath = currentPath + '/env/.env';
// We're concatenating the environment name to our filename to specify the correct env file!
envPath = basePath + '.' + process.env.ENVIRONMENT;
// console.log("the env path is", envPath);
// Check if the file exists, otherwise fall back to the production .env
const finalPath = fs.existsSync(envPath) ? envPath : basePath;
console.log("Selected env:", finalPath);
// Set the path parameter in the dotenv config
const fileEnv = dotenv.config({ path: finalPath }).parsed;
// reduce it to a nice object, the same as before (but with the variables from the file)
const envKeys = Object.keys(fileEnv).reduce((prev, next) => {
prev[`REACT_APP_${next}`] = JSON.stringify(fileEnv[next]);
return prev;
}, {});
let envs = ``
for (const k in envKeys) {
envs += `${k}=${envKeys[k]}n`
}
fs.writeFileSync(`${currentPath}/.env`, envs)
console.log('Environment variables copied to .env file.')
if (execString.indexOf('--exec:') >= 0) {
execString = execString.replace('--exec:', '')
console.log('Exec:', execString)
execSync(execString, { stdio: 'inherit' })
}

让我们构建环境文件

在parseEnv.js的相同级别创建一个文件夹env,并创建您的env文件

.env  ---> production file 
.env.development --> development environment 
.env.qa  --> Qa environment

示例:

.env.开发

TITLE=This is development 
API_URL=https://dev.example.com/api/v1.6
SECRET_KEY=xxxxxxxxxxxxxxxxxxxxxxxxx

.env

TITLE=This is Production
API_URL=https://prod.example.com/api/v1.6
SECRET_KEY=xxxxxxxxxxxxxxxxxxxxxxxxx

在你的index.js中,现在你可以通过调用来利用这些

const TITLE = process.env.REACT_APP_TITLE;  
const URL = process.env.REACT_APP_API_URL;

选项2:使用配置API。

您可以将所有配置放在JSON中,并根据域名放入数据库中。例如,假设您的开发总是从localhost:3000开始,qa将从https://qa.example.com等等

你可以构建一个像这样的数据库

域|配置

http://localhost:3000/{"标题":"这就是发展"}http://qa.example.com/{"标题":"这是QA"}

在初始化时,调用这个API并连接到配置服务器,然后配置服务器可以根据您的域为您提供这些配置。这里的优势是,你不需要单独构建,如果你愿意,你仍然可以在localhost:6000上运行你的Qa,你只需要单独添加一个数据库条目。无需在源代码中保留env文件。

最新更新