搜尋
首頁web前端js教程Markdown 中的互動元件

最近我實現了一個日曆,結果非常好,我想記錄該方法並與更廣泛的受眾分享。我真的很想在文章中得到我的工作的實際可測試結果。

我已經調整我的網站一段時間了,這個想法開始了下一次迭代。最終導致了另一個全面重建,但這個故事並不是關於我與完美主義的鬥爭。這是關於轉動這個:

HTML comes with a lot of ready to use and flexible elements, but date selector
has a handful of limitations and the need to write your own calendar / date
input emerges sooner rather than later. In this tutorial I'll walk you through
implementing a calendar view and show how you can extend its functionality to fit
your booking widget or dashboard filter.

Here's how the final result might look like:

<!--render:custom-calendar-component/CalendarExample.ssi.tsx-->

進入此:

Interactive Components in Markdown

設定

我的網站在 Deno 上運行,並從最近開始使用 Hono 和 Hono/JSX,但該方法適用於任何基於 JS 的運行時和 JSX。

正如您已經注意到的,部落格文章是帶有屬性的 Markdown 文件,這些屬性在構建時使用 Marked 和 Front Matter 轉換為靜態 HTML。

經過一番反覆思考,我決定了這個工作流程:

  • 我用markdown寫文章
  • 我在與文章相同的資料夾中建立了一個 JSX 元件
  • 我使用 HTML 註解在 Markdown 中「導入」元件
  • 它的神奇功效

註解需要某種前綴,例如渲染並且基本上只是該元件的路徑:

<!--render:custom-calendar-component/CalendarExample.ssi.tsx-->

也可以在路徑後添加道具,但對於我的用例來說,不需要它,所以我跳過了這一部分。

渲染 HTML

在瀏覽器上新增任何內容之前,我們需要從 JSX 元件渲染 HTML。為此,我們「只」需要使用自訂渲染器覆蓋 HTML 渲染邏輯:

export default class Renderer extends Marked.Renderer {
  constructor(private baseUrl: string, options?: Marked.marked.MarkedOptions) {
    super(options);
  }

  override html(html: string): string {
    const ssiMatch = /<!--render:(.+)-->/.exec(html);
    if (ssiMatch?.length) {
      const filename = ssiMatch[1];
      const ssi = SSIComponents.get(filename);
      if (!ssi) return html;
      const content = render(createElement(ssi.Component, {}));
      return [
        content,
        `<script type="module" src="%24%7Bssi.script%7D"></script>`,
      ].join("");
    }
    return html;
  }
}

邏輯非常簡單:檢查 html 字串是否符合 // 然後渲染 JSX。如果您手邊有組件,那就很容易了。

編譯元件

我的部落格內容是靜態產生的,所以我很自然地採用了相同的方法:

  • 掃描內容資料夾中的 *.ssi.tsx 元件(因此有字尾)
  • 建立一個檔案來匯入它們並將其新增到地圖中,以便我可以輕鬆地透過路徑檢索它們

這是我的建置腳本的樣子:

const rawContent = await readDir("./content");
const content: Record<string article> = {};
const ssi: Array<string> = [];

for (const pathname in rawContent) {
  if (pathname.endsWith(".ssi.tsx")) {
    ssi.push(pathname);
    continue;
  }
}

const scripts = await compileSSI(ssi.map((name) => `./content/${name}`));

const ssiContents = `
import type { FC } from 'hono/jsx';
const SSIComponents = new Map<string component: fc script: string>();
${
  scripts
    ? ssi
        .map(
          (pathname, i) =>
            `SSIComponents.set("${pathname}", { Component: (await import("./${pathname}")).default, script: "${scripts[i]}" })`
        )
        .join("\n")
    : ""
}
export default SSIComponents;
`;

await Deno.writeFile("./content/ssi.ts", new TextEncoder().encode(ssiContents));
</string></string></string>

不要太執著於 Deno 特定功能,它可以輕鬆地用 Node 或其他任何東西重寫。

神奇之處在於編寫類似 JavaScript 程式碼的文字檔。

這個腳本:

const ssiContents = `
import type { FC } from 'hono/jsx';
const SSIComponents = new Map<string component: fc script: string>();
${
  scripts
    ? ssi
        .map(
          (pathname, i) =>
            `SSIComponents.set("${pathname}", { Component: (await import("./${pathname}")).default, script: "${scripts[i]}" })`
        )
        .join("\n")
    : ""
}
export default SSIComponents;
`;
</string>

傳回以下字串:

import type { FC } from 'hono/jsx';
const SSIComponents = new Map<string component: fc script: string>();
SSIComponents.set("custom-calendar-component/CalendarExample.ssi.tsx", { Component: (await import("./custom-calendar-component/CalendarExample.ssi.tsx")).default, script: "/content/custom-calendar-component/CalendarExample.ssi.js" })
export default SSIComponents;

</string>

然後可以在渲染器中匯入和使用:)

寫程式碼的程式碼!魔法!並且在過程中沒有任何人工智慧受到傷害:只是你的老式元程式設計。

最後,最後一個難題是滋潤前端的組件。我使用 esbuild,但我個人打算將其切換到 Vite 或 HMR 附帶的任何其他工具。

儘管如此,它看起來是這樣的:

HTML comes with a lot of ready to use and flexible elements, but date selector
has a handful of limitations and the need to write your own calendar / date
input emerges sooner rather than later. In this tutorial I'll walk you through
implementing a calendar view and show how you can extend its functionality to fit
your booking widget or dashboard filter.

Here's how the final result might look like:

<!--render:custom-calendar-component/CalendarExample.ssi.tsx-->

您可以注意到一個虛擬入口點,其值為零,但會強制 esbuild 在自己的資料夾中建立檔案並具有可預測的路徑。

且 ssi-tsconfig.json 非常通用:

<!--render:custom-calendar-component/CalendarExample.ssi.tsx-->

在實際的前端水合作用中,我選擇了簡單的方法,並將其添加到我的 .ssi.tsx 檔案的底部:

export default class Renderer extends Marked.Renderer {
  constructor(private baseUrl: string, options?: Marked.marked.MarkedOptions) {
    super(options);
  }

  override html(html: string): string {
    const ssiMatch = /<!--render:(.+)-->/.exec(html);
    if (ssiMatch?.length) {
      const filename = ssiMatch[1];
      const ssi = SSIComponents.get(filename);
      if (!ssi) return html;
      const content = render(createElement(ssi.Component, {}));
      return [
        content,
        `<script type="module" src="%24%7Bssi.script%7D"></script>`,
      ].join("");
    }
    return html;
  }
}

我相信讀者會找到一種更優雅的方式來做到這一點,但僅此而已!

隨意調整程式碼(以下是儲存庫的連結),添加您自己的風格並分享您的想法!

Interactive Components in Markdown 瓦萊裡婭·VG / valeriavg.dev

以上是Markdown 中的互動元件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript數據類型:瀏覽器和nodejs之間是否有區別?JavaScript數據類型:瀏覽器和nodejs之間是否有區別?May 14, 2025 am 12:15 AM

JavaScript核心數據類型在瀏覽器和Node.js中一致,但處理方式和額外類型有所不同。 1)全局對像在瀏覽器中為window,在Node.js中為global。 2)Node.js獨有Buffer對象,用於處理二進制數據。 3)性能和時間處理在兩者間也有差異,需根據環境調整代碼。

JavaScript評論:使用//和 / * * / * / * /JavaScript評論:使用//和 / * * / * / * /May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript:開發人員的比較分析Python vs. JavaScript:開發人員的比較分析May 09, 2025 am 12:22 AM

Python和JavaScript的主要區別在於類型系統和應用場景。 1.Python使用動態類型,適合科學計算和數據分析。 2.JavaScript採用弱類型,廣泛用於前端和全棧開發。兩者在異步編程和性能優化上各有優勢,選擇時應根據項目需求決定。

Python vs. JavaScript:選擇合適的工具Python vs. JavaScript:選擇合適的工具May 08, 2025 am 12:10 AM

選擇Python還是JavaScript取決於項目類型:1)數據科學和自動化任務選擇Python;2)前端和全棧開發選擇JavaScript。 Python因其在數據處理和自動化方面的強大庫而備受青睞,而JavaScript則因其在網頁交互和全棧開發中的優勢而不可或缺。

Python和JavaScript:了解每個的優勢Python和JavaScript:了解每個的優勢May 06, 2025 am 12:15 AM

Python和JavaScript各有優勢,選擇取決於項目需求和個人偏好。 1.Python易學,語法簡潔,適用於數據科學和後端開發,但執行速度較慢。 2.JavaScript在前端開發中無處不在,異步編程能力強,Node.js使其適用於全棧開發,但語法可能複雜且易出錯。

JavaScript的核心:它是在C還是C上構建的?JavaScript的核心:它是在C還是C上構建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; sanInterpretedlanguagethatrunsonenginesoftenwritteninc.1)JavascriptwasdesignedAsignedAsalightWeight,drackendedlanguageforwebbrowsers.2)Enginesevolvedfromsimpleterterpretpretpretpretpreterterpretpretpretpretpretpretpretpretpretcompilerers,典型地,替代品。

JavaScript應用程序:從前端到後端JavaScript應用程序:從前端到後端May 04, 2025 am 12:12 AM

JavaScript可用於前端和後端開發。前端通過DOM操作增強用戶體驗,後端通過Node.js處理服務器任務。 1.前端示例:改變網頁文本內容。 2.後端示例:創建Node.js服務器。

Python vs. JavaScript:您應該學到哪種語言?Python vs. JavaScript:您應該學到哪種語言?May 03, 2025 am 12:10 AM

選擇Python還是JavaScript應基於職業發展、學習曲線和生態系統:1)職業發展:Python適合數據科學和後端開發,JavaScript適合前端和全棧開發。 2)學習曲線:Python語法簡潔,適合初學者;JavaScript語法靈活。 3)生態系統:Python有豐富的科學計算庫,JavaScript有強大的前端框架。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器