简体   繁体   English

是否可以使用reactjs CRA为不同的环境呈现不同的html

[英]Is it possible to render different html for different environments using reactjs CRA

Create React App generates a static html we use to bind our components to. Create React App会生成一个静态html,用于绑定组件。 I am wondering if we could change contents based on the environment we are in. 我想知道是否可以根据我们所处的环境更改内容。

<!DOCTYPE html>
<html lang="en">
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
  <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
  <title>React App</title>
</head>
<body>
  <div id="root"></div>
</body>

For example, if can I have title as "develop" & "production" depending on where the react app is running? 例如,是否可以根据React应用程序的运行位置将标题命名为"develop""production"

Can this be achieved just using reactjs env config file without any server side rendering? 是否可以仅使用reactjs env配置文件而无需任何服务器端渲染来实现?

edit: ...and without ejecting and dealing with webpack config? 编辑:...并且没有弹出和处理webpack配置?

I have a solution which can be done without using environment variables with an assumption your develop and production urls are different 我有一个解决方案,可以在不使用环境变量的情况下完成,前提是您的开发和生产网址不同

You can fetch the current url from window.location.href and based on the url you can change the title of the react app. 您可以从window.location.href获取当前网址,并根据该网址更改反应应用的标题。

However, I feel environment variables will be a better solution 但是,我认为环境变量将是更好的解决方案

You'd better to run npm run eject in your CRA object. 您最好在CRA对象中运行npm run eject run npm run eject you will find a folder called config , to change the HtmlWebpackPlugin from webpack.config.dev.js and webpack.config.prod.js : 您将找到一个名为config的文件夹,以从webpack.config.dev.jswebpack.config.prod.js更改webpack.config.prod.js

…
new HtmlWebpackPlugin({
  inject: true,
  template: **CHNAGE ME**,
…

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM