Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show build datetime on my react web app using create-react-app?

Tags:

reactjs

tl;dr version - I want to show the date of deployment of the production application on the footer of my application so that the users know exactly when the application was last updated.

I want it to be automatic, but I can't think of a way to capture the current date time during build and then parse it into html (jsx) to show them.

Update - Btw, I use CRA and have no plans of ejecting from it! At least not for this.

Context - Why do I want this? I have a production application in React that I don't have unrestricted access to. There were some issues raised on there and I was able to replicate it on my dev and I fixed the issues and deployed it (or I thought I did). But the issue remained on production and after more time debugging, I just asked for a lot of diagnostic information from them to check if there was something wrong with the production API or database etc. But it finally turned out that my deployment to production wasn't successful. I think that if I showed the last deployement date-time somewhere on the app, I could just ask that from the users rather than get into elaborate diagnostic information.

like image 482
Ragav Y Avatar asked Oct 28 '18 05:10

Ragav Y


People also ask

How do I check my React build time?

process. env. BUILD_DATE_TIME. That way you can show the approx date and time of your build.

How get current time in functional component react JS?

Open the console window with Ctrl + Shift + K and now you should be able to see the active hours after 3 seconds.


1 Answers

👋 I'm a Create React App maintainer!

Starting in Create React App 2 (react-scripts@^2.0) you can accomplish this via macros.

First, install preval.macro:

$ npm install --save preval.macro # if using npm
$ yarn add preval.macro # if using yarn

Next, in the file you want to render a build timestamp in, include preval.macro:

import preval from 'preval.macro'

Finally, you can create a constant and use it in your app like so:

const dateTimeStamp = preval`module.exports = new Date().toLocaleString();`

Here's a full example:

import React, { Component } from 'react'
import logo from './logo.svg'
import './App.css'
import preval from 'preval.macro'

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Build Date: {preval`module.exports = new Date().toLocaleString();`}.
          </p>
        </header>
      </div>
    )
  }
}

export default App
like image 180
Joe Haddad Avatar answered Sep 29 '22 14:09

Joe Haddad