提问者:小点点

在使用express服务器为React应用程序提供服务时,将环境变量注入React应用程序


我正在开发一个应用程序,它将后端和前端作为单个项目的一部分,后端除了是API之外,还通过以下方式为前端提供静态文件:

const frontendDir = appRoot.resolve("../frontend/build")
app.use(express.static(frontendDir))
app.get("*", (req, res) => res.sendFile(path.resolve(frontendDir, "index.html")))

有没有一种方法可以在发送这些文件之前对它们进行预处理,以注入一些服务器可以访问但客户机显然不能访问的环境变量?

我试图使一些变量可以访问,如sentry_dsnheroku_release_versionheroku_release_created_at等。


共1个答案

匿名用户

我不知道这会有什么帮助,但我认为您可以使用模板引擎将数据传递到前端。就像handlebars:

const Handlebars = require('handlebars')

Handlebars.registerHelper('prod', () => {
  return process.env.NODE_ENV === 'production';
})

在html文件中:

<div class="some-content">   
  {{#if prod}}
    <p>Seen only in production</p>
  {{/if}}
  
  <p>This is some example text</p>
</div>