无法更改 REACT_APP_XXXXX 环境。编译后的变量。他们正在永久“融入”应用程序。
我通过从后端提供动态 JSON 清单文件解决了这个问题。该应用程序加载 JSON 文件并读取其值。这种方法的一种变体是从后端提供一个 Javascript js 文件。该脚本执行一个在全局窗口对象中设置一些变量的函数。
这是一个节点 express 应用程序的 sn-p,它以 JSON 和 JS 文件的形式提供清单。
const express = require('express')
const app = express()
const manifest = {
appTheme: process.env.APP_THEME,
foo: "bar"
};
const cacheTimeoutSec = 600
class ManifestController {
static getJS(req, res) {
/// Generate IIFE function that sets window.serverManifest object
let fileChunks = [
'(function(){',
'var serverManifest=',
JSON.stringify(manifest),
'; window.serverManifest = serverManifest',
'})()',
].join('');
res.set('Cache-Control', `public, max-age=${cacheTimeoutSec}`);
res.setHeader('content-type', 'text/javascript');
res.write(fileChunks);
res.end();
}
static getJSON(req, res) {
res.json(manifest);
}
}
// Serve manifest in JS
app.get('/server-manifest.js', ManifestController.getJS);
// Serve manifest as JSON
app.get('/server-manifest.json', ManifestController.getJSON);
选项 1:
React 应用程序手动从您的后端获取 JSON 文件(例如 https://api.mybackend.com/server-manifest.json)并对数据进行操作。
选项 2:
像这样在html文件头中包含<script>标签
<html lang="en">
<head>
<script src="https://api.mybackend.com/server-manifest.js"></script>
<title>Home</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
</body>
</html>
如果你把它放在<head> 中,浏览器会加载脚本并执行它。该脚本在全局 window.serverManifest 对象中设置清单,React 应用现在可以随时访问该对象。