lit tailwindcss vite模板

卓能文發表於2024-08-18
pnpm create vite@latest my-project -- --template lit
cd my-project
pnpm install -D tailwindcss postcss autoprefixer sass-embedded
npx tailwindcss init -p

tailwindcss.config.js:

/** @type {import('tailwindcss').Config} */
export default {
  corePlugins: {
    preflight: false,
  },
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx,css,scss}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

src/global.d.ts:

declare module "*.scss";
declare module "*.scss?inline";
declare module "*.css";
declare module "*.css?inline";
declare module "*.html";

src/tailwind.global.css:

@tailwind base;
@tailwind components;
@tailwind utilities;

src/tailwind.element.ts:

import { LitElement, unsafeCSS } from "lit";

import style from "./tailwind.global.css?inline";

const tailwindElement = unsafeCSS(style);

export const TailwindElement = (style: string) =>
	class extends LitElement {
		static styles = [tailwindElement, unsafeCSS(style)];
	};

src/my.counter.scss:

p {
  @apply bg-red-200;

  b {
    @apply text-orange-500;
  }
}

my.counter.ts:

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

import style from "./my.counter.scss?inline";

@customElement("my-counter")
export class MyCounter extends TailwindElement(style) {
	@property({ type: Number })
	count = 0;
	@property()
  	name?: string = "World";

	render() {
		const styles = { color: "" };
		if (this.count >= 0) {
			styles.color = "green";
		} else {
			styles.color = "red";
		}
		return html`
      <div>
		<p>
			Hello,
			<b>${this.name}</b>
			!
		</p>
        <button class="rounded bg-green-500 w-5" @click=${this._onDec} part="button"> - </button>
        count is: <span style=${styleMap(styles)}>${this.count}</span>
        <button class="rounded bg-green-500 w-5" @click=${this._onInc} part="button"> + </button>
      </div>
    `;
	}

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

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

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

index.html:

<!doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <link rel="icon" type="image/svg+xml" href="/vite.svg" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Vite + Lit + TS</title>
  <script type="module" src="/src/my.counter.ts"></script>
</head>

<body>
  <my-counter></my-counter>
</body>

</html>

相關文章