记录一下 本文使用 react-app-rewired+env-cmd+progress-bar-webpack-plugin实现 打包或运行时会显示进度条 无痛点 全在如下代码片段 注释比较清晰
源码 https://gitee.com/tothis/react-record/tree/master/base
yarn add react-app-rewired env-cmd progress-bar-webpack-plugin -D
使用env-cmd的 js方式配置环境变量 指定的js文件会在项目运行/打包前预先执行
实现步骤
- 使用react-app-rewired重写配置 并添加progress-bar-webpack-plugin进度条插件
// 根路径config-overrides.js
const chalk = require('chalk')
// progress 进度条插件
, progressBarPlugin = require('progress-bar-webpack-plugin')({
width: 60
, format: `${chalk.green('build')} [ ${chalk.cyan(':bar')} ]`
+ ` ${chalk.cyan(':msg')} ${chalk.red('(:percent)')}`
, clear: true
})
module.exports = (config, env) => {
// 添加插件
config.plugins.push(progressBarPlugin)
return config
}
- 配置version.js
// 此处定义的环境变量会覆盖env文件定义的环境变量
module.exports = Promise.resolve({
REACT_APP_VERSION: '1.0',
REACT_APP_BUILD_TIME: new Date().getTime()
})
package.json
{
"scripts": {
"start": "env-cmd -f version.js react-app-rewired start",
"build": "env-cmd -f version.js react-app-rewired build",
"test": "react-app-rewired test",
"eject": "react-scripts eject"
}
}
- 使用
在执行yarn build或yarn start时会出现进度条
项目版本号使用
import React, { Component } from 'react'
export default class extends Component {
render() {
const a = 'font-weight:bold;color:#fff;background:#606060;padding:5px 0;border-radius:4px 0 0 4px;';
const b = 'font-weight:bold;color:#fff;background:#ff8585;padding:5px 0;border-radius:0 4px 4px 0;';
return (
<p>{console.log(`%c build-time %c ${process.env.REACT_APP_BUILD_TIME} `, a, b)}</p>
)
}
}