Dependency-free HTML diffing library written in TypeScript.
npm install @yeger/html-diff
Dependency-free HTML diffing library written in TypeScript.
> This is a fork of diff-htmls and html-diff-ts, which are TypeScript ports
of HtmlDiff.NET which is itself a C# port of
the Ruby implementation, HtmlDiff.
> This fork drops CJS support to fix various issues in modern ESM projects.
pnpm i @yeger/html-diff
Comparing two HTML blocks, and returns a meshing of the two that includes and elements. The classes of these elements are ins.diffins for new code,del.diffdel for removed code, and del.diffmod and ins.diffmod for sections of code
that have been changed.
For "special tags" (primarily style tags such as and ), ins.mod
elements are inserted with the new styles.
Options:
- blocksExpression - list of Regular Expressions which will be treated as one block (token) instead of being divided
- exp - Regular Expression for token itself
- compareBy - Regular Expression for part of the token by which will be compared
made
``ts
import { diff } from '@yeger/html-diff'
const oldHtml = '
Some old html here
'Some new html goes here
'const result = diff(oldHtml, newHtml)
`
Result:
`html`
Some old >new html here
Visualization:
`diff`
Some
- old
+ new
html here
The tokenizer works by running the diff on words, but sometimes this isn't ideal.
For example, it may look clunky when a date is edited from 12 Jan 2022 to 14 Feb 2022.
It might be neater to treat the diff on the entire date rather than the independent tokens.
You can achieve this using AddBlockExpression.
Note, the Regex example is not meant to be exhaustive to cover all dates.
If text matches the expression, the entire phrase is included as a single token to be compared, and that results in a much neater output.
`ts
import { diff } from '@yeger/html-diff'
const oldHtml = '
12.11.2022
'15.12.2022
'const result = diff(oldHtml, newHtml, { blocksExpression: [{ exp: dateRegexp }] })
`
Result:
`html
12.11.2022 15.12.2022
Visualization:
`diff
- 12.11.2022
+ 15.12.2022
`$3
No diff
`ts
import { diff } from '@yeger/html-diff'// "src" attr is different but "title" - is the same
const oldHtml = '
'
// "src" attr is different but "title" - is the same
const newHtml = '
'
const result = diff(oldHtml, newHtml, {
blocksExpression: [
{
// match
tag
exp: /
/g,
// compare only by title="" attribute
compareBy: /title="[\s\S]+?"/g,
},
],
})
`Result:
Will return the new string without comparison to old one - because title attribute is the
same
`html

`Has diff
`ts
import { diff } from '@yeger/html-diff'// "title" attr is different
const oldHtml = '
'
// "title" attr is different
const newHtml = '
'
const result = diff(oldHtml, newHtml, {
blocksExpression: [
{
// match
tag
exp: /
/g,
// compare only by title="" attribute
compareBy: /title="[\s\S]+?"/g,
},
],
})
`Result:
Will return the new string with diff to old one - because title attribute has changed
`html


`Visualization:
`diff
- 
+ 
``