astro中浏览器端使用lit编写的components

在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>
posted @ 2024-08-20 07:40  卓能文  阅读(29)  评论(0)    收藏  举报