使用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 或装饰器声明属性以支持响应式更新。
相关推荐
武子康5 分钟前
Video VAE 不是末端编解码器:5 维-潜网格-主模型 Token 的“表示合同“
人工智能·llm·agent
Sunlly7 分钟前
Transcript 不是 Context:用五组实验拆解 OpenClaw 的上下文生命周期
人工智能
ttwuai9 分钟前
AI 生成后台改数据后,操作日志别只记按钮:Go + MySQL 怎么验
数据库·人工智能·mysql·golang
糖果店的幽灵24 分钟前
我用 Codex + Remotion,做了一条唐朝纸片分层动画
人工智能
KaMeidebaby30 分钟前
卡梅德生物技术快报 | 核酸适配体文库测序:核酸适配体文库测序的技术原理、实验流程与数据解析
前端·网络·数据库·人工智能·算法
阿里云大数据AI技术44 分钟前
AI 时代,零售商超如何用多模态数据"看见"每一排货架?
人工智能
一RTOS一1 小时前
【无标题】
人工智能·鸿道实时操作系统·国产嵌入式操作系统选型·智算控一体
cian_1 小时前
我把 Anthropic 官方的 Claude Cookbook 拆成了 30+ 个能直接跑的例子
人工智能
秦先生在广东1 小时前
`claude-video /watch`:给 Claude 装上“眼睛“看视频的工程实现与边界分析
人工智能
极客猴子1 小时前
会议记录APP怎么选 2026年实测功能对比与使用指南
人工智能·xcode