使用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 或装饰器声明属性以支持响应式更新。
相关推荐
weisian1512 小时前
入门篇--知名企业-3-Google DeepMind:从AlphaGo到AGI,AI如何改写人类未来?
人工智能
郝学胜-神的一滴2 小时前
机器学习数据集完全指南:从公开资源到Sklearn实战
人工智能·python·程序人生·机器学习·scikit-learn·sklearn
偶信科技2 小时前
聚焦“一点”洞察海洋:偶信科技单点海流计引领精准观测新趋势
人工智能·科技·偶信科技·ocean·海洋仪器·单点海流计
汤姆yu2 小时前
基于yolov8的深度学习垃圾分类检测系统
人工智能·深度学习
菠菠萝宝2 小时前
从传统后端到AI智能驱动:Java + AI 生态深度实战技术总结
java·人工智能·ai·llm·知识图谱·ai编程·rag
独孤--蝴蝶2 小时前
AI人工智能-大模型的演进-第十一周(上)(小白)
人工智能·深度学习·自然语言处理
喝拿铁写前端2 小时前
AI 驱动前端开发覆盖的能力全景拆解
前端·javascript·人工智能
Dev7z2 小时前
基于Matlab的Logistic混沌映射语音信号加密与解密系统设计与仿真
人工智能·语音识别
道可云2 小时前
2026年企业AI应用演进趋势与CIO布局策略
人工智能·百度