javascript - ใช้ google-diff-match-patch ใน angular
ฉันอยากจะใช้ google diff/match/patch lib ในแอป Angular เพื่อแสดงความแตกต่างระหว่างข้อความสองชุด
ฉันจะใช้งานแบบนี้:
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();
คำตอบ #1
คุณจำเป็นต้องนำเข้าแพ็กเกจ npm สำหรับโปรเจกต์ angular ใน package.json
"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);
}
}
นี่คือโค้ดตัวอย่าง
คำตอบ #2
ต่อยอดจากคำตอบของ @Shashank -- เพื่อให้แน่ใจในความปลอดภัยของชนิดข้อมูล คุณยังสามารถติดตั้ง 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_patch class ที่ตั้งชื่อได้ค่อนข้างแย่เท่านั้น (ซึ่งดูเหมือน function) — ซึ่งคุณพยายามจะรันตั้งแต่แรก!
อย่างไรก็ตาม TypeScript ยังรองรับการเปลี่ยนชื่อการนำเข้า ซึ่งคุณสามารถนำเข้าคลาสที่สามารถสร้างอินสแตนซ์ได้ที่เราคุ้นเคย:
import { diff_match_patch as DiffMatchPatch } from 'diff-match-patch';
เมื่อทำการนำเข้าอย่างถูกต้องแล้ว คุณจะสามารถเพลิดเพลินกับ IntelliSense และสิ่งอื่น ๆ ได้:
