astro中瀏覽器端使用lit編寫的components

卓能文發表於2024-08-20

在vite + lit中除錯好的程式碼my.counter.ts:

import { LitElement, css, html } from "lit";
import { customElement, property } from "lit/decorators.js";
import { styleMap } from "lit/directives/style-map.js";

@customElement("my-counter")
export class MyCounter extends LitElement {
	@property({ type: Number })
	count = 0;

	render() {
		const styles = { color: "" };
		if (this.count >= 0) {
			styles.color = "green";
		} else {
			styles.color = "red";
		}
		return html`
      <div>
        <button @click=${this._onDec} type="button"> - </button>
        count is: <span style=${styleMap(styles)}>${this.count}</span>
        <button @click=${this._onInc} type="button"> + </button>
      </div>
    `;
	}

	private _onDec() {
		this.count--;
	}

	private _onInc() {
		this.count++;
	}

	static styles = css`
    button {
      border-radius: 4px;
      border: 1px solid transparent;
      background-color: limegreen;
    }
  `;
}

declare global {
	interface HTMLElementTagNameMap {
		"my-counter": MyCounter;
	}
}

在astro中如果使用lit整合,採用的是SSR,瀏覽器端無互動功能,即使採用<MyCounter client:visible|only|load />等都無瀏覽器互動效果。經查,astro並不生成用於互動的js。

為了繞過這個限制,採用bun對lit程式碼進行編譯:

bun build src/components/my.counter.ts --outfile public/my.counter.js --minify

然後,在src/pages/demo.mdx中,採用如下方式:

---
layout: ../layouts/Layout.astro
---

# Welcome

<my-counter />
<script type="module" src="my.counter.js"></script>

或在starlightsrc/content/docs/demo.mdx:

---
title: Demonstrate lit components
description: Demonstrate lit components.
template: splash
---

<my-counter />
<script type="module" src="my.counter.js"></script>

相關文章