Skip to content

代码/文件对比

就像 github/gitlab 代码提交后,查看代码的变动一样
通过两个 js 库即可实现:diff2htmljsdiff

对比效果图

1. diff2html

作用:将 diff 转为好看的 html 页面
官网地址:https://diff2html.xyz/
仓库地址:https://github.com/rtfpessoa/diff2html

安装

bash
npm install diff2html

在 Vue.js 中使用

vue
<template>
  <div v-html="prettyHtml" />
</template>

<script>
import * as Diff2Html from 'diff2html';
import 'diff2html/bundles/css/diff2html.min.css';

export default {
  data() {
    return {
      diffs:
        '--- a/server/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go\n+++ b/server/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go\n@@ -1035,6 +1035,17 @@ func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (\n \n // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n \n+func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {\n+\tr0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)))\n+\tn = int(r0)\n+\tif e1 != 0 {\n+\t\terr = errnoErr(e1)\n+\t}\n+\treturn\n+}\n+\n+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n+\n func read(fd int, p []byte) (n int, err error) {\n \tvar _p0 unsafe.Pointer\n \tif len(p) > 0 {\n',
    };
  },
  computed: {
    prettyHtml() {
      return Diff2Html.html(this.diffs, {
        drawFileList: true,
        matching: 'lines',
        outputFormat: 'side-by-side',
      });
    },
  },
};
</script>
  • 接受的 diff 参数必须是统一格式的 diff 或超集格式的 git diff

2. jsdiff

作用:生成两段文本的差异
官网地址:https://github.com/kpdecker/jsdiff

安装

bash
npm install diff

在 Vue.js 中使用

vue
const jsDiff = require('diff');

this.diffs = jsDiff.createTwoFilesPatch(
  'file1name', 'file2name',
  'file1data', 'file2data'
);
  • 主要使用 createTwoFilesPatch 方法