一招搞定HTML文件注入分支和日期信息

155 阅读1分钟

在工作中,如果线上迭代环境太多,每个环境都对应不同的分支,测试提个bug就贴个url信息,每次都得根据域名去看这个环境用的哪个分支的代码,有没有和这相同困扰的小伙伴?今天就来聊一聊如何在静态资源HTML文件注入当前分支信息和日期信息吧。

创建js脚本文件

我是在scripts文件夹下面创建了个inject.js文件 image.png

获取当前分支

const { execSync } = require('child_process');
execSync('git symbolic-ref --short -q HEAD')

读取build文件夹的html文件

const htmlPath = path.join(__dirname, '../', 'build', 'index.html');
const html = fs.readFileSync(htmlPath); // 同步读取文件

此时读取出来的内容是buffer数据格式

image.png 所以需要将buffer数据格式转化为字符

let result = html.toString(); // buffer数据格式转化为字符

image.png

信息注入

 const date = new Date();
    // 写入分支和日期
    result =
      `<!--\n
          * @Branch: ${currentBranch}\n
          * @Date: ${date}\n
           -->\n` + result;
           
 fs.writeFileSync(htmlPath, result);

完整代码

const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

const injectInfo = () => {
  // 获取当前分支
  const currentBranch = execSync('git symbolic-ref --short -q HEAD');

  const htmlPath = path.join(__dirname, '../', 'build', 'index.html'); // 找到build目录下的html文件
  const html = fs.readFileSync(htmlPath); // 同步读取文件
  let result = html.toString(); // buffer数据格式转化为字符
  try {
    const date = new Date();
    // 写入分支和日期
    result =
      `<!--\n
          * @Branch: ${currentBranch}\n
          * @Date: ${date}\n
           -->\n` + result;
  } catch (error) {
    console.error('获取Git分支失败:', error);
  }
  fs.writeFileSync(htmlPath, result);
};

injectInfo();

执行脚本

在build命令后加上脚本的执行命令即可

"scripts": {
    "start": "node scripts/start.js",
    "build": "webpack --config webpack.prod.js && node scripts/inject.js"
  },

执行 yarn build

image.png

可以看到已经将分支信息和时间点注入进html文件里面了👏👏👏🏻。