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

The solution from joe-haddad is working well. Here is a drop-in component you can use like <VersionNumber />. This will display something like:

enter image description here

import React       from 'react';
import moment      from 'moment';
import packageJson from '../../../package.json';
import preval      from 'preval.macro';

const buildTimestamp = preval`module.exports = new Date().getTime();`;

class Component extends React.Component {
    getDateString = () => {
        const lastUpdateMoment = moment.unix(buildTimestamp / 1000);
        const formattedDate    = lastUpdateMoment.format('DD.MM.YYYY HH:mm:ss');

        return formattedDate;
    };

    render () {
        return (
            <div>
                {packageJson.version}
                {'.'}
                {buildTimestamp}
                {' '}
                {'('}
                {this.getDateString()}
                {')'}
            </div>
        );
    }
}

Component.propTypes = {};

Component.defaultProps = {};

export default Component;

👋 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

Tags:

Reactjs