これらのライブラリはすべて「差分(diff)」を扱いますが、対象とするデータ構造や最終的な目的が異なります。deep-diff は JavaScript オブジェクトのネストされた構造変化を検出します。diff はテキストや文字列の差分を計算するための標準的なアルゴリズムを実装しています。diff2html は計算された差分データを、人間が読みやすい HTML 形式に変換して表示します。diff3 は 3 Way マージ(共通の祖先と 2 つの変更版)を処理するためのロジックを提供し、競合解決に使用されます。
JavaScript エコシステムには「差分」を扱うライブラリが多数存在しますが、それぞれが解決しようとしている問題のレイヤーが異なります。deep-diff、diff、diff2html、diff3 は、データ比較から可視化、マージまで、変更管理のライフサイクルをカバーしています。これらがどのように役割分担しているか、実装レベルで比較します。
変更を検出する際、最も重要なのは「何を比較するか」です。JavaScript オブジェクトの構造変化を捉えるのか、それともテキストの行や文字の変化を捉えるのかで、選ぶべきライブラリが完全に異なります。
deep-diff は JavaScript オブジェクトの深い比較に特化しています。
// deep-diff: オブジェクトの比較
const Diff = require('deep-diff');
const lhs = { name: 'Alice', role: 'Dev' };
const rhs = { name: 'Alice', role: 'Admin' };
const changes = Diff.diff(lhs, rhs);
// 出力: [{ kind: 'E', path: ['role'], lhs: 'Dev', rhs: 'Admin' }]
diff は文字列の比較に特化しています。
// diff: 文字列の比較
import { diffLines } from 'diff';
const oldText = 'line 1\nline 2';
const newText = 'line 1\nline 3';
const changes = diffLines(oldText, newText);
// 出力: [{ value: 'line 1\n', added: false, removed: false }, ...]
diff3 は 3 つのテキスト入力(祖先、版 A、版 B)を扱います。
// diff3: 3 Way テキストマージ
const diff3 = require('diff3');
const ancestor = 'line 1\nline 2';
const versionA = 'line 1\nline A';
const versionB = 'line 1\nline B';
const result = diff3.merge(ancestor, versionA, versionB);
// 出力: マージ結果または競合情報
diff2html は入力として差分文字列(Unified Diff)を取ります。
diff パッケージなどの出力を HTML に変換する橋渡し役です。// diff2html: 差分文字列の受け取り
const Diff2Html = require('diff2html');
const diffString = '--- a/file.js\n+++ b/file.js\n@@ -1 +1 @@\n-line 2\n+line 3';
const html = Diff2Html.html(diffString);
// 出力: 色付きの HTML 文字列
差分を人間に伝える際、コンソールログで済ます場合もあれば、リッチな UI として表示する場合もあります。この目的の違いがライブラリ選定を分けます。
deep-diff はデータ構造を返します。
// deep-diff: データ処理用
changes.forEach(change => {
if (change.kind === 'E') {
console.log(`Changed ${change.path.join('.')} from ${change.lhs} to ${change.rhs}`);
}
});
diff は差分オブジェクトの配列を返します。
// diff: 基礎データ用
changes.forEach(part => {
const color = part.added ? 'green' : part.removed ? 'red' : 'grey';
// 自作のレンダラーで色付けするなど
});
diff2html は完成された HTML を返します。
// diff2html: 表示用
const htmlOutput = Diff2Html.html(diffString, {
drawFileList: true,
matching: 'lines',
outputFormat: 'side-by-side'
});
document.getElementById('diff-view').innerHTML = htmlOutput;
diff3 はマージ結果のテキストを返します。
// diff3: 結果テキスト用
if (result.conflict) {
console.log('Merge conflict detected in text block');
} else {
console.log(result.ok); // マージ済みのテキスト
}
これらのライブラリは、パイプラインの異なる段階で動作します。これらを組み合わせることで、強力な変更管理システムを構築できます。
deep-diff は比較フェーズ専用です。
diff も比較フェーズ専用ですが、テキスト向けです。
diff3 は解決フェーズで使用します。
diff2html は表示フェーズで使用します。
パッケージのメンテナンス状況は、長期プロジェクトにおいて重要な要素です。
deep-diff は比較的安定しています。
diff は非常に活発に保守されています。
diff2html は UI 要件に依存します。
diff3 は注意が必要です。
diff3 パッケージは更新が停滞している可能性があります。node-diff3 などの代替を検討するか、コードを直接確認してください。// 注意: diff3 の使用例
// 本番環境で使用する前に、メンテナンス状況を確認してください
const diff3 = require('diff3');
// 代替案: const diff3 = require('node-diff3');
これら 4 つのパッケージは異なる役割を持ちますが、変更管理という共通の目標を持っています。
// どのライブラリも「変化」を出力する
// deep-diff: 変更パス
// diff: 変更行
// diff3: 変更結果
diff の出力を diff2html に渡すなど、連携して機能します。// diff と diff2html の連携例
import { createTwoFilesPatch } from 'diff';
const patch = createTwoFilesPatch('a.txt', 'b.txt', oldStr, newStr);
const html = Diff2Html.html(patch);
// 手実装すると複雑になるネスト比較も
// deep-diff なら一行で処理可能
const changes = Diff.diff(complexObjA, complexObjB);
| 機能 | deep-diff | diff | diff2html | diff3 |
|---|---|---|---|---|
| 主な入力 | JavaScript オブジェクト | 文字列(テキスト) | 差分文字列(Unified Diff) | 3 つの文字列 |
| 主な出力 | 変更オブジェクトの配列 | 差分パーツの配列 | HTML 文字列 | マージ済みテキスト |
| 用途 | 状態比較、JSON 監視 | コード比較、テキスト解析 | 差分の可視化、UI 表示 | マージ、競合解決 |
| 可視化 | ❌ (データのみ) | ❌ (データのみ) | ✅ (HTML 生成) | ❌ (テキストのみ) |
| 保守性 | ✅ 安定 | ✅ 非常に安定 | ✅ 安定 | ⚠️ 確認が必要 |
diff はテキスト比較の必須ライブラリです。コードエディタやレビュー機能を作るならまずこれを選びます。
deep-diff はフロントエンドの状態管理に最適です。React や Vue のコンポーネント間でデータがどう変わったか追跡するのに便利です。
diff2html は表示層のショートカットです。自分で HTML を生成する手間を省きたい場合に有効ですが、依存関係の増加には注意してください。
diff3 は特殊な用途です。オンラインエディタで同時編集をマージするような高度な機能が必要な場合のみ検討し、保守状況をよく確認してください。
結論: 多くのフロントエンドプロジェクトでは、diff(計算用)と diff2html(表示用)の組み合わせ、あるいは deep-diff(状態監視用)が最も頻繁に役立ちます。diff3 は要件が明確な場合のみ導入を検討しましょう。
アプリケーションの状態管理や、JSON データの構造変更をプログラムで検出したい場合に選択します。テキストではなくオブジェクトのキーや値の変化を追跡する必要があるシーン — 例えば Redux のステート比較や設定ファイルの更新検知 — に最適です。
コードレビューツールや、テキストファイルの比較など、文字列ベースの差分計算が必要な場合に選択します。行単位や単語単位など、粒度を細かく設定して差分を取得できるため、汎用性が高いライブラリです。
計算された差分情報を Web ブラウザ上で視覚的に表示したい場合に選択します。diff パッケージなどで生成された統一フォーマット(Unified Diff)の文字列を、色付きの HTML コードに変換する役割を担います。
バージョン管理システムのような、2 つの変更版を共通の祖先からマージするロジックが必要な場合に選択します。ただし、メンテナンス状況を確認し、より現代的な代替案がないか検討した上で採用を検討してください。
deep-diff is a javascript/node.js module providing utility functions for determining the structural differences between objects and includes some utilities for applying differences across objects.
npm install deep-diff
Possible v1.0.0 incompatabilities:
deep-diff does a pre-order traversal of the object graph, however, when it encounters an array, the array is processed from the end towards the front, with each element recursively processed in-order during further descent.npm install deep-diff
var diff = require('deep-diff')
// or:
// const diff = require('deep-diff');
// const { diff } = require('deep-diff');
// or:
// const DeepDiff = require('deep-diff');
// const { DeepDiff } = require('deep-diff');
// es6+:
// import diff from 'deep-diff';
// import { diff } from 'deep-diff';
// es6+:
// import DeepDiff from 'deep-diff';
// import { DeepDiff } from 'deep-diff';
<script src="https://cdn.jsdelivr.net/npm/deep-diff@1/dist/deep-diff.min.js"></script>
In a browser,
deep-diffdefines a global variableDeepDiff. If there is a conflict in the global namespace you can restore the conflicting definition and assigndeep-diffto another variable like this:var deep = DeepDiff.noConflict();.
In order to describe differences, change revolves around an origin object. For consistency, the origin object is always the operand on the left-hand-side of operations. The comparand, which may contain changes, is always on the right-hand-side of operations.
var diff = require('deep-diff').diff;
var lhs = {
name: 'my object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'elements']
}
};
var rhs = {
name: 'updated object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'more', 'elements', { than: 'before' }]
}
};
var differences = diff(lhs, rhs);
v 0.2.0 and above The code snippet above would result in the following structure describing the differences:
[ { kind: 'E',
path: [ 'name' ],
lhs: 'my object',
rhs: 'updated object' },
{ kind: 'E',
path: [ 'details', 'with', 2 ],
lhs: 'elements',
rhs: 'more' },
{ kind: 'A',
path: [ 'details', 'with' ],
index: 3,
item: { kind: 'N', rhs: 'elements' } },
{ kind: 'A',
path: [ 'details', 'with' ],
index: 4,
item: { kind: 'N', rhs: { than: 'before' } } } ]
Differences are reported as one or more change records. Change records have the following structure:
kind - indicates the kind of change; will be one of the following:
N - indicates a newly added property/elementD - indicates a property/element was deletedE - indicates a property/element was editedA - indicates a change occurred within an arraypath - the property path (from the left-hand-side root)lhs - the value on the left-hand-side of the comparison (undefined if kind === 'N')rhs - the value on the right-hand-side of the comparison (undefined if kind === 'D')index - when kind === 'A', indicates the array index where the change occurreditem - when kind === 'A', contains a nested change record indicating the change that occurred at the array indexChange records are generated for all structural differences between origin and comparand. The methods only consider an object's own properties and array elements; those inherited from an object's prototype chain are not considered.
Changes to arrays are recorded simplistically. We care most about the shape of the structure; therefore we don't take the time to determine if an object moved from one slot in the array to another. Instead, we only record the structural
differences. If the structural differences are applied from the comparand to the origin then the two objects will compare as "deep equal" using most isEqual implementations such as found in lodash or underscore.
When two objects differ, you can observe the differences as they are calculated and selectively apply those changes to the origin object (left-hand-side).
var observableDiff = require('deep-diff').observableDiff;
var applyChange = require('deep-diff').applyChange;
var lhs = {
name: 'my object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'elements']
}
};
var rhs = {
name: 'updated object',
description: 'it\'s an object!',
details: {
it: 'has',
an: 'array',
with: ['a', 'few', 'more', 'elements', { than: 'before' }]
};
observableDiff(lhs, rhs, function (d) {
// Apply all changes except to the name property...
if (d.path[d.path.length - 1] !== 'name') {
applyChange(lhs, rhs, d);
}
});
A standard import of var diff = require('deep-diff') is assumed in all of the code examples. The import results in an object having the following public properties:
diff(lhs, rhs, prefilter, acc) — calculates the differences between two objects, optionally prefiltering elements for comparison, and optionally using the specified accumulator.observableDiff(lhs, rhs, observer, prefilter) — calculates the differences between two objects and reports each to an observer function, optionally, prefiltering elements for comparison.applyDiff(target, source, filter) — applies any structural differences from a source object to a target object, optionally filtering each difference.applyChange(target, source, change) — applies a single change record to a target object. NOTE: source is unused and may be removed.revertChange(target, source, change) reverts a single change record to a target object. NOTE: source is unused and may be removed.diffThe diff function calculates the difference between two objects.
lhs - the left-hand operand; the origin object.rhs - the right-hand operand; the object being compared structurally with the origin object.prefilter - an optional function that determines whether difference analysis should continue down the object graph.acc - an optional accumulator/array (requirement is that it have a push function). Each difference is pushed to the specified accumulator.Returns either an array of changes or, if there are no changes, undefined. This was originally chosen so the result would be pass a truthy test:
var changes = diff(obja, objb);
if (changes) {
// do something with the changes.
}
The prefilter's signature should be function(path, key) and it should return a truthy value for any path-key combination that should be filtered. If filtered, the difference analysis does no further analysis of on the identified object-property path.
const diff = require('deep-diff');
const assert = require('assert');
const data = {
issue: 126,
submittedBy: 'abuzarhamza',
title: 'readme.md need some additional example prefilter',
posts: [
{
date: '2018-04-16',
text: `additional example for prefilter for deep-diff would be great.
https://stackoverflow.com/questions/38364639/pre-filter-condition-deep-diff-node-js`
}
]
};
const clone = JSON.parse(JSON.stringify(data));
clone.title = 'README.MD needs additional example illustrating how to prefilter';
clone.disposition = 'completed';
const two = diff(data, clone);
const none = diff(data, clone,
(path, key) => path.length === 0 && ~['title', 'disposition'].indexOf(key)
);
assert.equal(two.length, 2, 'should reflect two differences');
assert.ok(typeof none === 'undefined', 'should reflect no differences');
When contributing, keep in mind that it is an objective of deep-diff to have no package dependencies. This may change in the future, but for now, no-dependencies.
Please run the unit tests before submitting your PR: npm test. Hopefully your PR includes additional unit tests to illustrate your change/modification!
When you run npm test, linting will be performed and any linting errors will fail the tests... this includes code formatting.
Thanks to all those who have contributed so far!