0

Create React App generates a static html we use to bind our components to. 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?

Can this be achieved just using reactjs env config file without any server side rendering?

edit: ...and without ejecting and dealing with webpack config?

4
  • 2
    If you mean the title tag you can use Helmet github.com/nfl/react-helmet Commented Jun 29, 2018 at 7:16
  • 1
    Got help for the title in CRA:- You can actually define a variable in env file and reference that in your title like so: <title>%REACT_APP_MY_PAGE_TITLE%</title> This way you can define different titles for different envs like env.local, env.production e.t.c This was so neat, i hope it helps you Commented Jun 30, 2018 at 19:01
  • Question: what do you mean "without dealing with webpack config"? Do you not deploy your code with a build step to ensure your bundles built for the environment it's running in? Commented Jun 30, 2018 at 19:09
  • create-react-app's boilerplate takes care of the configs and for simple apps, you do not need to modify webpack - whcih requires you to eject github.com/facebook/create-react-app/blob/master/packages/… Commented Jun 30, 2018 at 19:15

2 Answers 2

1

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.

However, I feel environment variables will be a better solution

Sign up to request clarification or add additional context in comments.

Comments

0

You'd better to run npm run eject in your CRA object. you will find a folder called config, to change the HtmlWebpackPlugin from webpack.config.dev.js and webpack.config.prod.js:

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

1 Comment

thanks. sorry I just updated the question to not consider ejecting. Yours is probably a good solution but I prefer not dealing with configs too much.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.