deep-diff vs diff vs diff2html vs diff3
変更検出と可視化ライブラリの選定ガイド
deep-diffdiffdiff2htmldiff3類似パッケージ:

変更検出と可視化ライブラリの選定ガイド

これらのライブラリはすべて「差分(diff)」を扱いますが、対象とするデータ構造や最終的な目的が異なります。deep-diff は JavaScript オブジェクトのネストされた構造変化を検出します。diff はテキストや文字列の差分を計算するための標準的なアルゴリズムを実装しています。diff2html は計算された差分データを、人間が読みやすい HTML 形式に変換して表示します。diff3 は 3 Way マージ(共通の祖先と 2 つの変更版)を処理するためのロジックを提供し、競合解決に使用されます。

npmのダウンロードトレンド

3 年

GitHub Starsランキング

統計詳細

パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
deep-diff00-08年前MIT
diff09,121616 kB145日前BSD-3-Clause
diff2html03,3502.02 MB333ヶ月前MIT
diff301411.9 kB2-MIT

deep-diff vs diff vs diff2html vs diff3: 変更検出と可視化のアーキテクチャ比較

JavaScript エコシステムには「差分」を扱うライブラリが多数存在しますが、それぞれが解決しようとしている問題のレイヤーが異なります。deep-diffdiffdiff2htmldiff3 は、データ比較から可視化、マージまで、変更管理のライフサイクルをカバーしています。これらがどのように役割分担しているか、実装レベルで比較します。

🎯 対象データ:オブジェクト構造 vs テキスト文字列

変更を検出する際、最も重要なのは「何を比較するか」です。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 は文字列の比較に特化しています。

  • 行単位、単語単位、文字単位など、粒度を指定して差分を計算します。
  • Git の差分出力のような、テキストベースの変更検出に適しています。
// 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)を扱います。

  • 主にマージ処理に使用されるため、入力も出力もテキストベースです。
  • 2 つの変更が競合しているかどうかを判定します。
// 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 文字列

🎨 可視化:データ構造 vs HTML 表示

差分を人間に伝える際、コンソールログで済ます場合もあれば、リッチな UI として表示する場合もあります。この目的の違いがライブラリ選定を分けます。

deep-diff はデータ構造を返します。

  • UI での表示は開発者自身で実装する必要があります。
  • 変更箇所をプログラムで処理しやすい形式です。
// deep-diff: データ処理用
changes.forEach(change => {
  if (change.kind === 'E') {
    console.log(`Changed ${change.path.join('.')} from ${change.lhs} to ${change.rhs}`);
  }
});

diff は差分オブジェクトの配列を返します。

  • これもそのまま表示するのではなく、別のロジックでレンダリングします。
  • 自作の Diff UI を構築する際の基礎データとして使います。
// 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); // マージ済みのテキスト
}

🔄 処理フロー:比較 vs マージ vs 変換

これらのライブラリは、パイプラインの異なる段階で動作します。これらを組み合わせることで、強力な変更管理システムを構築できます。

deep-diff は比較フェーズ専用です。

  • 入力:2 つのオブジェクト
  • 出力:変更リスト
  • 用途:状態の監視、変更のログ記録

diff も比較フェーズ専用ですが、テキスト向けです。

  • 入力:2 つの文字列
  • 出力:差分パーツの配列
  • 用途:コード比較、テキスト編集履歴

diff3 は解決フェーズで使用します。

  • 入力:3 つの文字列(祖先、A、B)
  • 出力:マージ済み文字列または競合情報
  • 用途:同時編集の統合、コンフリクト解決

diff2html は表示フェーズで使用します。

  • 入力:Unified Diff 文字列
  • 出力:HTML 文字列
  • 用途:プルリクエスト画面、変更履歴ビュー

⚠️ 保守性と代替案の検討

パッケージのメンテナンス状況は、長期プロジェクトにおいて重要な要素です。

deep-diff は比較的安定しています。

  • 長年使用されており、API も変更されにくいです。
  • オブジェクト比較のデファクトスタンダードとして信頼できます。

diff は非常に活発に保守されています。

  • 多くのプロジェクトで依存されており、信頼性が高いです。
  • 文字列比較が必要な場合は第一候補になります。

diff2html は UI 要件に依存します。

  • 特定の HTML 出力が必要な場合に有効ですが、軽量な代替ライブラリも存在します。
  • 依存関係が増えるため、バンドルサイズへの影響を考慮する必要があります。

diff3 は注意が必要です。

  • npm に登録されている diff3 パッケージは更新が停滞している可能性があります。
  • 重要なマージロジックに使用する場合は、より現代的な node-diff3 などの代替を検討するか、コードを直接確認してください。
// 注意: diff3 の使用例
// 本番環境で使用する前に、メンテナンス状況を確認してください
const diff3 = require('diff3'); 
// 代替案: const diff3 = require('node-diff3');

🤝 共通点:変更管理の基盤

これら 4 つのパッケージは異なる役割を持ちますが、変更管理という共通の目標を持っています。

1. 📝 変更の明確化

  • すべて「何が変わったか」を明確にするためのツールです。
  • 暗黙的な状態変化を防ぎ、デバッグを容易にします。
// どのライブラリも「変化」を出力する
// deep-diff: 変更パス
// diff: 変更行
// diff3: 変更結果

2. 🔗 パイプライン構成可能

  • これらを組み合わせて使用することが可能です。
  • 例えば diff の出力を diff2html に渡すなど、連携して機能します。
// diff と diff2html の連携例
import { createTwoFilesPatch } from 'diff';
const patch = createTwoFilesPatch('a.txt', 'b.txt', oldStr, newStr);
const html = Diff2Html.html(patch);

3. 🛠️ 開発者体験の向上

  • 手実装すると複雑なロジックをライブラリが肩代わりします。
  • エッジケース(空配列、特殊文字など)の処理を任せられます。
// 手実装すると複雑になるネスト比較も
// deep-diff なら一行で処理可能
const changes = Diff.diff(complexObjA, complexObjB);

📊 比較サマリー

機能deep-diffdiffdiff2htmldiff3
主な入力JavaScript オブジェクト文字列(テキスト)差分文字列(Unified Diff)3 つの文字列
主な出力変更オブジェクトの配列差分パーツの配列HTML 文字列マージ済みテキスト
用途状態比較、JSON 監視コード比較、テキスト解析差分の可視化、UI 表示マージ、競合解決
可視化❌ (データのみ)❌ (データのみ)✅ (HTML 生成)❌ (テキストのみ)
保守性✅ 安定✅ 非常に安定✅ 安定⚠️ 確認が必要

💡 最終的な推奨事項

diff はテキスト比較の必須ライブラリです。コードエディタやレビュー機能を作るならまずこれを選びます。

deep-diff はフロントエンドの状態管理に最適です。React や Vue のコンポーネント間でデータがどう変わったか追跡するのに便利です。

diff2html は表示層のショートカットです。自分で HTML を生成する手間を省きたい場合に有効ですが、依存関係の増加には注意してください。

diff3 は特殊な用途です。オンラインエディタで同時編集をマージするような高度な機能が必要な場合のみ検討し、保守状況をよく確認してください。

結論: 多くのフロントエンドプロジェクトでは、diff(計算用)と diff2html(表示用)の組み合わせ、あるいは deep-diff(状態監視用)が最も頻繁に役立ちます。diff3 は要件が明確な場合のみ導入を検討しましょう。

選び方: deep-diff vs diff vs diff2html vs diff3

  • deep-diff:

    アプリケーションの状態管理や、JSON データの構造変更をプログラムで検出したい場合に選択します。テキストではなくオブジェクトのキーや値の変化を追跡する必要があるシーン — 例えば Redux のステート比較や設定ファイルの更新検知 — に最適です。

  • diff:

    コードレビューツールや、テキストファイルの比較など、文字列ベースの差分計算が必要な場合に選択します。行単位や単語単位など、粒度を細かく設定して差分を取得できるため、汎用性が高いライブラリです。

  • diff2html:

    計算された差分情報を Web ブラウザ上で視覚的に表示したい場合に選択します。diff パッケージなどで生成された統一フォーマット(Unified Diff)の文字列を、色付きの HTML コードに変換する役割を担います。

  • diff3:

    バージョン管理システムのような、2 つの変更版を共通の祖先からマージするロジックが必要な場合に選択します。ただし、メンテナンス状況を確認し、より現代的な代替案がないか検討した上で採用を検討してください。

deep-diff のREADME

deep-diff

CircleCI

NPM

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.

Install

npm install deep-diff

Possible v1.0.0 incompatabilities:

  • elements in arrays are now processed in reverse order, which fixes a few nagging bugs but may break some users
    • If your code relied on the order in which the differences were reported then your code will break. If you consider an object graph to be a big tree, then 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.

Features

  • Get the structural differences between two objects.
  • Observe the structural differences between two objects.
  • When structural differences represent change, apply change from one object to another.
  • When structural differences represent change, selectively apply change from one object to another.

Installation

npm install deep-diff

Importing

nodejs

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';

browser

<script src="https://cdn.jsdelivr.net/npm/deep-diff@1/dist/deep-diff.min.js"></script>

In a browser, deep-diff defines a global variable DeepDiff. If there is a conflict in the global namespace you can restore the conflicting definition and assign deep-diff to another variable like this: var deep = DeepDiff.noConflict();.

Simple Examples

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

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/element
    • D - indicates a property/element was deleted
    • E - indicates a property/element was edited
    • A - indicates a change occurred within an array
  • path - 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 occurred
  • item - when kind === 'A', contains a nested change record indicating the change that occurred at the array index

Change 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.

Changes

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);
  }
});

API Documentation

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.

diff

The diff function calculates the difference between two objects.

Arguments

  • 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.
}

Pre-filtering Object Properties

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');

Contributing

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!