score:41
👋 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
score:0
Set a process environment using webpack. You can save the value to a local json file and read from it with an increment during the compilation.
score:0
function getClientEnvironment(publicUrl) {
const raw = Object.keys(process.env)
.filter(key => REACT_APP.test(key))
.reduce(
(env, key) => {
env[key] = process.env[key];
return env;
},
{
// Useful for determining whether we’re running in production mode.
// Most importantly, it switches React into the correct mode.
NODE_ENV: process.env.NODE_ENV || 'development',
REACT_APP_DATE_TIME: new Date().toDateString(),
// Useful for resolving the correct path to static assets in `public`.
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
// This should only be used as an escape hatch. Normally you would put
// images into the `src` and `import` them in code to get their paths.
PUBLIC_URL: publicUrl,
}
);
// Stringify all values so we can feed into Webpack DefinePlugin
const stringified = {
'process.env': Object.keys(raw).reduce((env, key) => {
env[key] = JSON.stringify(raw[key]);
return env;
}, {}),
};
return { raw, stringified };
}
module.exports = getClientEnvironment;
The old solution will also work. Please check the code again. As i can see the proper value in my app.
score:0
A contribution to Joe Haddat's answer; if you want to illustrate the build date by using preval.macro
in the viewer timezone instead of the environment timezone which builds the app, here is how to do it;
render() {
const buildDate = preval`module.exports = new Date();`
return (
<div>Build Date: {new Date(buildDate).toLocaleString()}</div>
)
}
This will save the build date, but turning it into a locale string will still happen on runtime, on the browser where the viewer timezone is used.
score:5
The solution from joe-haddad is working well. Here is a drop-in component you can use like <VersionNumber />
. This will display something like:
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;
Source: stackoverflow.com
Related Query
- How to show build datetime on my react web app using create-react-app?
- How to create multiple page app using react
- How to not show warnings in Create React App
- How to inject port and host using ENV variable in Create React App Proxy settings?
- How to analyze create react app build size and reduce it?
- How to build react app using Dockerfile.dev and Yarn
- How to create React App including Web3 using create-react-app? I am getting Module not found Error. BREAKING CHANGE: webpack < 5 used
- How to determine the order of css in my create react app build with webpack and customize-cra?
- How create a react app with a specific version using the npx command?
- How can I get rid of the `Node "13.0.0-nightly20190802452b393c1f"` so that I can be able to create a react app using the `create-react-app` tool?
- How to show links only on App component not on child component in React using React Router?
- How to import image(SVG or PNG) in React using Create React App
- How to show the dialog everywhere in the app on clicking a button using react and typescript?
- How to create react app using create-react-app with reactjs 15 version
- I create a build of my react app and connected with electron.js. now how to connect my backend from server folder with electron
- How To Build a web.config for a react app using azure + IISNode + express
- How can we show or hide components inside OverReact (library to build react components using dart ) according to conditions?
- How to create a Google web app using Google Apps Script, React, and MobX
- How to compress build files in create react app without ejecting?
- How to test/mock API calls using JEST in Create react app
- How do I manage to display in browser my React production build by using Spring Boot web server?
- How to create a React app directly in the current folder
- How to show a loading indicator in React Redux app while fetching the data?
- How to deploy a React App on Apache web server
- How to create and run a development build of an application using create-react-app configuration
- How can remove console.log in the production build of a React application created using create-react-app?
- how to create common helper class in React JS using ES6 which is used by another component?
- Swiper React | How to create custom navigation/pagination components using React refs?
- How to integrate azure ad into a react web app that consumes a REST API in azure too
- How import object from external JS file in React JS using web pack
More Query from same tag
- How to fetch data that needs to be fetched only once
- d3.js in React for 3d charts
- React JS - Passing functions for child components
- Can't Use Context API while making a tree
- Module not found: Can't resolve 'firebase/index'
- How to make the text to align properly in map pin marker css?
- How to load page contain ReactJs into other page using jquery ajax
- How can i use handleScroll in my current component?
- problems with deploying react project on netlify
- Jest, Enzyme, React, Next.js, Typescript .default is not a constructor
- Implement custom infinite scrolling in react
- react-select async doesn't work
- Tailwindcss not rendering in ExpressJS/React app
- Conditional Rendering in React application using tsx
- React import from parent directory
- Dynamically Bind data to InnerHTML in react.js
- Setting up Webpack 5 template with Express
- How to deal with state changes in functions with Jest and Enzyme
- "object Object" showing as input value with Formik forms on ReactJS
- seemore/hide post with markdown content
- getting error in if else condition in react js
- How to resolve eslient token error that is not further specified?
- Load data in a function with .map
- How to get the entire string until the + sign that changes in length?
- Limit the upload number of image in reactjs
- Cannot find module 'map-cache'
- How to stretch my background using css in react ? (handle overflow)
- How to insert SVG file using React , having it's path/url?
- How can i define a default value for react-select v1
- re-rendering issue using react hooks