跳至主要內容

在 Deno 中使用 LinkeDOM

LinkeDOM 是類 DOM 的命名空間,用於在未實作 DOM 的環境中,例如 Deno。

LinkeDOM 專注於快速且實作對伺服器端渲染有用的功能。它可能會允許您執行無效的 DOM 操作。 deno-domjsdom 專注於正確性。雖然目前 deno-dom 在某些情況下比 LinkeDOM 慢,但兩者都比 jsdom 快得多,因此如果您需要正確性或與伺服器端渲染無關的功能,請考慮 deno-dom。

雖然 LinkeDOM 在 Deno CLI 中運作,但它不會進行類型檢查。雖然提供的類型在使用像 VSCode 這樣的編輯器時運作良好,但嘗試像 Deno 預設在執行時對其進行嚴格類型檢查,它將會失敗。如果您使用 tsc 來對程式碼進行類型檢查,情況也是一樣。維護者已表示他們對 修復此問題 沒有興趣。這表示對於 Deno,您需要使用 --no-check=remote 來避免診斷停止執行您的程式。

LinkedDOM 與 deno_dom 一起在 Deno Deploy 中執行,但 jsdom 沒有。

基本範例

此範例將採用一個測試字串,並將其解析為 HTML,並根據它產生一個 DOM 結構。然後它將查詢該 DOM 結構,挑選出它遇到的第一個標題,並印出該標題的文字內容

import { DOMParser } from "https://esm.sh/linkedom";
import { assert } from "https://deno.land/std@0.220.0/assert/mod.ts";

const document = new DOMParser().parseFromString(
`<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello from Deno</title>
</head>
<body>
<h1>Hello from Deno</h1>
<form>
<input name="user">
<button>
Submit
</button>
</form>
</body>
</html>`,
"text/html",
);

assert(document);
const h1 = document.querySelector("h1");
assert(h1);

console.log(h1.textContent);

替代 API

parseHTML() 對於某些 SSR 工作負載來說可能更適合。這類似於 jsdom 的 JSDOM() 函式,在於它提供了一個 window 範圍的「沙盒」,您可以使用它來存取 document 範圍外的 API。例如

import { parseHTML } from "https://esm.sh/linkedom";

const { document, customElements, HTMLElement } = parseHTML(`<!DOCTYPE html>
<html lang="en">
<head>
<title>Hello from Deno</title>
</head>
<body>
<h1>Hello from Deno</h1>
<form>
<input name="user">
<button>
Submit
</button>
</form>
</body>
</html>`);

customElements.define(
"custom-element",
class extends HTMLElement {
connectedCallback() {
console.log("it works 🥳");
}
},
);

document.body.appendChild(document.createElement("custom-element"));

document.toString(); // the string of the document, ready to send to a client