使用Vite+ Lit 构建webcomponent 组件

使用 Vite + Lit 构建 WebComponent 组件

初始化项目

创建一个新的 Vite 项目并选择适合的模板(如 vanillavanilla-ts)。运行以下命令:

复制代码
npm create vite@latest my-lit-element --template vanilla
cd my-lit-element
npm install

安装 Lit 依赖:

复制代码
npm install lit
配置 Vite

确保 Vite 配置文件支持 WebComponent 开发。在 vite.config.js 中,添加以下配置以启用自定义元素:

复制代码
import { defineConfig } from 'vite';

export default defineConfig({
  build: {
    lib: {
      entry: 'src/my-component.js',
      name: 'MyComponent',
      fileName: 'my-component',
      formats: ['es']
    }
  }
});
创建 Lit 组件

src 目录下创建组件文件(如 my-component.js)。使用 Lit 的 htmlcss 模板标签定义组件:

复制代码
import { LitElement, html, css } from 'lit';

class MyComponent extends LitElement {
  static styles = css`
    :host {
      display: block;
      padding: 16px;
      color: #333;
    }
  `;

  static properties = {
    message: { type: String }
  };

  constructor() {
    super();
    this.message = 'Hello, Lit!';
  }

  render() {
    return html`<div>${this.message}</div>`;
  }
}

customElements.define('my-component', MyComponent);
开发与构建

启动开发服务器:

复制代码
npm run dev

构建生产版本:

复制代码
npm run build

构建后会生成 dist 目录,包含可直接使用的 ES 模块文件。

使用组件

在 HTML 中通过模块导入方式使用组件:

复制代码
<!DOCTYPE html>
<html>
  <head>
    <script type="module" src="/src/my-component.js"></script>
  </head>
  <body>
    <my-component message="Custom Message"></my-component>
  </body>
</html>
可选:TypeScript 支持

若使用 TypeScript,安装类型定义并更新组件文件为 .ts

复制代码
npm install --save-dev @types/webcomponents @types/trusted-types

示例 TypeScript 组件:

复制代码
import { LitElement, html, css } from 'lit';
import { customElement, property } from 'lit/decorators.js';

@customElement('my-component')
export class MyComponent extends LitElement {
  @property({ type: String }) message = 'Hello, Lit!';

  static styles = css`
    :host {
      display: block;
      padding: 16px;
    }
  `;

  render() {
    return html`<div>${this.message}</div>`;
  }
}
注意事项
  • 确保组件名称包含连字符(如 my-component),符合 WebComponents 规范。
  • 使用 :host 选择器定义组件根样式。
  • 通过 static properties 或装饰器声明属性以支持响应式更新。
相关推荐
美酒没故事°1 天前
Open WebUI安装指南。搭建自己的自托管 AI 平台
人工智能·windows·ai
云烟成雨TD1 天前
Spring AI Alibaba 1.x 系列【6】ReactAgent 同步执行 & 流式执行
java·人工智能·spring
AI攻城狮1 天前
用 Obsidian CLI + LLM 构建本地 RAG:让你的笔记真正「活」起来
人工智能·云原生·aigc
鸿乃江边鸟1 天前
Nanobot 从onboard启动命令来看个人助理Agent的实现
人工智能·ai
lpfasd1231 天前
基于Cloudflare生态的应用部署与开发全解
人工智能·agent·cloudflare
俞凡1 天前
DevOps 2.0:智能体如何接管故障修复和基础设施维护
人工智能
comedate1 天前
[OpenClaw] GLM 5 关于电影 - 人工智能 - 的思考
人工智能·电影评价
财迅通Ai1 天前
6000万吨产能承压 卫星化学迎来战略窗口期
大数据·人工智能·物联网·卫星化学
liliangcsdn1 天前
Agent Memory智能体记忆系统的示例分析
数据库·人工智能·全文检索
GISer_Jing1 天前
Page-agent MCP结构
前端·人工智能