ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

如何手写一个 webpack 插件:实现 vuecli3 打包时生成一个 git 分支版本信息的文件?

2021-07-02 18:58:05  阅读:274  来源: 互联网

标签:插件 git vuecli3 -- execSync let 提交 date


分析问题

  1. 首先需要我们获取项目当前所在分支的信息,比如项目打包时:当前的版本分支,最新代码提交人,时间,提交的信息
  2. 然后将这些信息生成到 txt 文本里面,这个文件是在打包的时候添加到打包目录里的

解决问题

先用 vuecli3 脚手架生成一个项目,在此基础上,我们在根目录新建一个 webpack-plugin 的文件夹,在这个文件夹里新建一个 branch-version-webpack-plugin.js 文件。如下图:

在这里插入图片描述

1.获取 git 分支版本信息

参考下面的资料:

// 同步子进程
const execSync = require('child_process').execSync;
// 时间格式生成
function dateFormat(date) {
  let y = date.getFullYear();
  let M = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1;
  let d = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();
  let h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours();
  let m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes();
  let s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
  return `${y}-${M}-${d} ${h}:${m}:${s}`;
}
// 获取当前git分支信息
function getBranchVersionInfo() {
  // 当前分支名 git name-rev --name-only HEAD 这个命令会在终端输出你当前的版本或标签信息。
  let vName = execSync('git name-rev --name-only HEAD').toString().trim();
  // 提交的commit hash
  let commitHash = execSync('git show -s --format=%H').toString().trim();
  // 提交人姓名
  let name = execSync('git show -s --format=%cn').toString().trim();
  // 提交日期
  let date = dateFormat(new Date(execSync('git show -s --format=%cd').toString()));
  // 提交描述
  let message = execSync('git show -s --format=%s').toString().trim();
  return `
    当前分支名:${vName}\n
    提交的hash:${commitHash}\n
    提交人姓名:${name}\n
    提交日期:${date}\n
    提交描述:${message}
  `;
}

2.打包时文件生成

这个可以参考 html-webpack-plugin 插件的实现。

在这里插入图片描述

重点看这个:Pushes the content of the given filename to the compilation assets.

在这里插入图片描述

关于 hooks 使用 emit:输出目录之前执行。 https://v4.webpack.js.org/api/compiler-hooks/#emit

emit:

  • AsyncSeriesHook
  • Executed right before emitting assets to output dir.
  • Callback Parameters: compilation

实现代码如下:

// 创建分支版本类
class BranchVersionWebpackPlugin {
  constructor(options) {
    // options 为调用时传的参数
    console.log('凯小默的 BranchVersionWebpackPlugin 被调用!', options);
  }
  /**
   * compiler: webpack 的实例 所有的内容
   * compilation: 本次打包的内容
   * */ 

  apply(compiler) {
    // 异步方法,生成打包目录时:生成文件
    compiler.hooks.emit.tapAsync('BranchVersionWebpackPlugin', (compilation, cb) => {
      // 添加分支版本信息文件
      let branchVersionInfo = getBranchVersionInfo();
      compilation.assets['version.txt'] = {
        source: () => branchVersionInfo,
        size: () => branchVersionInfo.length
      }
      cb();
    })
  }
}

完整代码使用

使用:我们找到我们的配置文件 vue.config.js 在里面添加下面代码:

// 分支版本信息
const BranchVersionWebpackPlugin = require('./webpack-plugin/branch-version-webpack-plugin');

module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? '/dist/' : '/dist',
  // 将构建好的文件输出到哪里
  outputDir: 'dist',
  pages: {
    index: {
      entry: 'src/index/main.js',
      template: 'src/index/tpl.html',
      filename: 'index.html',
      title: 'kaimo 测试页',
      chunks: ['chunk-vendors', 'chunk-common', 'index']
    }
  },
  configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      // 版本信息文件生成
      config.plugins.push(new BranchVersionWebpackPlugin());
    }
  }
};

branch-version-webpack-plugin.js 代码如下:

// 同步子进程
const execSync = require('child_process').execSync;
// 时间格式生成
function dateFormat(date) {
  let y = date.getFullYear();
  let M = date.getMonth() + 1 < 10 ? `0${date.getMonth() + 1}` : date.getMonth() + 1;
  let d = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate();
  let h = date.getHours() < 10 ? `0${date.getHours()}` : date.getHours();
  let m = date.getMinutes() < 10 ? `0${date.getMinutes()}` : date.getMinutes();
  let s = date.getSeconds() < 10 ? `0${date.getSeconds()}` : date.getSeconds();
  return `${y}-${M}-${d} ${h}:${m}:${s}`;
}
// 获取当前git分支信息
function getBranchVersionInfo() {
  // 当前分支名
  let vName = execSync('git name-rev --name-only HEAD').toString().trim();
  // 提交的commit hash
  let commitHash = execSync('git show -s --format=%H').toString().trim();
  // 提交人姓名
  let name = execSync('git show -s --format=%cn').toString().trim();
  // 提交日期
  let date = dateFormat(new Date(execSync('git show -s --format=%cd').toString()));
  // 提交描述
  let message = execSync('git show -s --format=%s').toString().trim();
  return `
    当前分支名:${vName}\n
    提交的hash:${commitHash}\n
    提交人姓名:${name}\n
    提交日期:${date}\n
    提交描述:${message}
  `;
}
// 创建分支版本类
class BranchVersionWebpackPlugin {
  constructor(options) {
    // options 为调用时传的参数
    console.log('凯小默的 BranchVersionWebpackPlugin 被调用!', options);
  }
  /**
   * compiler: webpack 的实例 所有的内容
   * compilation: 本次打包的内容
   * */ 

  apply(compiler) {
    // 异步方法,生成打包目录时:生成文件
    compiler.hooks.emit.tapAsync('BranchVersionWebpackPlugin', (compilation, cb) => {
      // 添加分支版本信息文件
      let branchVersionInfo = getBranchVersionInfo();
      compilation.assets['version.txt'] = {
        source: () => branchVersionInfo,
        size: () => branchVersionInfo.length
      }
      cb();
    })
  }
}

module.exports = BranchVersionWebpackPlugin;

测试结果

添加好之后我们执行打包命令:

npm run build

控制台打包成功,undefined 表示使用插件没有传参。

在这里插入图片描述

然后我们看一下 dist 打包目录是否生成 version.txt 文件:发现是有的,如下图所示

在这里插入图片描述

接下来我们提交一下代码:然后在打包看看:发现信息已经更新了,当然你也可以切换分支测试一下。

在这里插入图片描述

标签:插件,git,vuecli3,--,execSync,let,提交,date
来源: https://blog.csdn.net/kaimo313/article/details/118416228

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有