Skip to main content
nulldepdoc

独自 Web Components の作り方#

nulldepdoc では、ビルドツールや React を追加せずに、チーム独自のインタラクティブなコンポーネントを Markdown 内に埋め込めます。

3 ステップで追加する#

1. static/ にバニラ JS の Custom Element を置く#

タグ名には必ずハイフン(-)を含めます(Web 標準の仕様)。

static/hello-counter.js
class HelloCounter extends HTMLElement {
  connectedCallback() {
    if (this._initialized) return;
    this._initialized = true;

    let count = Number(this.getAttribute('start') || 0);
    const btn = document.createElement('button');
    btn.type = 'button';
    btn.className = 'nd-icon-btn';

    const update = () => {
      btn.textContent = `クリック回数: ${count}`;
    };
    btn.addEventListener('click', () => {
      count += 1;
      update();
    });
    update();
    this.append(btn);
  }
}

if (!customElements.get('hello-counter')) {
  customElements.define('hello-counter', HelloCounter);
}

2. nulldepdoc.config.json に登録する#

nulldepdoc.config.json
{
  "customScripts": ["/hello-counter.js"]
}

3. Markdown にそのまま書く#

markdown
<hello-counter start="1"></hello-counter>

実際に動いている例(<site-dep-compare>)#

このドキュメントサイト自身も、static/dep-compare.js と static/site-custom.css を登録して以下の比較ウィジェットを動かしています。ボタンを押して表示を切り替えられます。

JavaScript が無効な環境では、このフォールバック説明文がそのまま表示されます。

Built with nulldepdoc itself — 0 npm dependencies.