如何使用create-react-app在我的React Web应用上显示构建日期时间?

时间:2018-10-28 05:57:06

标签: reactjs

tl; dr版本-我想在应用程序的页脚上显示生产应用程序的部署日期,以便用户确切知道应用程序的最新更新时间。

我希望它是自动的,但是我想不出一种方法来捕获构建期间的当前日期时间,然后将其解析为html(jsx)以显示它们。

更新-顺便说一句,我使用的是CRA,并且没有从中退出的计划!至少不是这个。

上下文-为什么要这样做? 我在React中有一个生产应用程序,我没有不受限制的访问权限。那里出现了一些问题,我能够在我的开发人员上复制它,然后我解决了问题并部署了它(或者我认为我做到了)。但是问题仍然存在于生产中,经过更多时间的调试后,我只是从他们那里索取了许多诊断信息,以检查生产API或数据库等是否存在问题。但是最终结果证明,我对生产的部署不是不成功。我认为,如果我在应用程序的某个位置显示了最后一次部署的日期时间,我可以向用户询问,而不是深入了解诊断信息。

4 个答案:

答案 0 :(得分:9)

我是Create React App的维护者!

从Create React App 2(react-scripts@^2.0)开始,您可以通过宏完成此操作。

首先,安装preval.macro

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

接下来,在要呈现构建时间戳记的文件中,包括preval.macro

import preval from 'preval.macro'

最后,您可以创建一个常量,然后像这样在应用程序中使用它:

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

这是一个完整的例子:

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

答案 1 :(得分:0)

使用webpack设置流程环境。您可以将值保存到本地json文件,并在编译过程中以递增方式从中读取。

答案 2 :(得分: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;

旧的解决方案也将起作用。请再次检查代码。如我所见,我的应用程序具有适当的价值。

答案 3 :(得分:0)

joe-haddad的解决方案运行良好。这是一个可以像<VersionNumber />一样使用的嵌入式组件。这将显示如下内容:

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;