【问题标题】:Using google-diff-match-patch in angular在 Angular 中使用 google-diff-match-patch
【发布时间】:2020-12-13 18:29:18
【问题描述】:

我想在 Angular 应用程序中使用 google diff/match/patch lib 来显示两个文本之间的差异。

我的用法是这样的:

public ContentHtml: SafeHtml;
compare(text1: string, text2: string):void {
        var dmp = new diff_match_patch();

        dmp.Diff_Timeout = 1;
        dmp.Diff_EditCost = 4;

        var d = dmp.diff_main(text1, text2);
        dmp.diff_cleanupSemantic(d);
        var ds = dmp.diff_prettyHtml(d);

        this.ContentHtml = this._sanitizer.bypassSecurityTrustHtml(ds);
}

问题是,如何为这条线导入diff_match_patch
var dmp = new diff_match_patch();

【问题讨论】:

    标签: javascript angular typescript google-diff-match-patch


    【解决方案1】:

    基于@Shashank 的回答——为确保类型安全,您还可以通过以下方式安装corresponding type defs

    npm i -D @types/diff-match-patch
    or 
    yarn add -D @types/diff-match-patch
    

    这些类型定义自 2017 年以来没有太大变化,这意味着您将无法使用

    import DiffMatchPatch from 'diff-match-patch';
    

    因为这些类型没有默认导出——它们只导出名称相当糟糕的diff_match_patchclass(看起来像一个函数)——你试图第一时间跑!

    不过,typescript 也支持import renaming,您可以使用它导入我们都习惯的可实例化类:

    import { diff_match_patch as DiffMatchPatch } from 'diff-match-patch';
    

    正确导入后,您将能够享受智能感知等功能:

    【讨论】:

      【解决方案2】:

      您需要在package.json 中导入 Angular 项目的 npm 包。

      "diff-match-patch": "^1.0.5",
      

      并在组件中导入为:

      import { Component } from '@angular/core';
      import DiffMatchPatch from 'diff-match-patch';
      @Component({
        selector: 'my-app',
        templateUrl: './app.component.html',
        styleUrls: ['./app.component.css']
      })
      export class AppComponent {
        name = 'Angular';
      
        getDiff() {
          var dmp = new DiffMatchPatch();
          var diff = dmp.diff_main('Hello', 'Hallo');
          // Result: [(-1, "Hell"), (1, "G"), (0, "o"), (1, "odbye"), (0, " World.")]
          dmp.diff_cleanupSemantic(diff);
          // Result: [(-1, "Hello"), (1, "Goodbye"), (0, " World.")]
          console.log(diff);
        }
      
      }
      
      

      Here is a demo code

      【讨论】:

      • 我是否也需要将包添加到 webpack 或其他东西?添加此内容后,我在加载 Uncaught TypeError: Cannot read property 'call' of undefined at __webpack_require__ (bootstrap:79) 时出错,我不知道为什么
      • @Sam :我尝试在 Angular 的小型演示项目中使用相同的代码,当我使用 ng serve 并尝试使用 ng build --prod 时,一切正常。运行 ng s 时是否收到错误消息?对于提供的错误,我找到的解决方案很少:stackoverflow.com/questions/41549923/…。请让我了解更多有关您的实施的信息。
      • @Sam: 运气好吗?
      • 最后就像清理缓存一样简单:/对不起,我花了这么长时间......
      • @Sam :很高兴听到它得到了修复。干杯!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 1970-01-01
      相关资源
      最近更新 更多