使用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 或装饰器声明属性以支持响应式更新。
相关推荐
yingyuecom8 分钟前
Seedance 2.5正式发布:映悦AI迎来“更长、更可控、更极致”的视频生成时代
人工智能·gpt·chatgpt·prompt·aigc
MindUp17 分钟前
告别排版焦虑:从 PPT 模板到 AI 生成工具的个人使用体验与效率对比
人工智能·powerpoint
martindelophy28 分钟前
Codex Chrome 插件 + Timeline Studio:构建可编辑的 AI 视频剪辑 Agent 工作流
前端·人工智能·chrome
AIkk8630 分钟前
大文件怎么压缩变小方便传输?本地压缩+云端方案对比测评
人工智能
薛定e的猫咪33 分钟前
(ICLR2026)MORL‑FB:从无奖励强化学习视角重新审视多目标强化学习
人工智能·深度学习·机器学习
行业研究员41 分钟前
腾讯云ADP:智能体平台封神榜
人工智能·microsoft·腾讯云·智能体·智能体平台·腾讯云adp
问天_观心1 小时前
零基础在windows环境下的WSL使用llamafactory(一)
人工智能·windows·python·神经网络·语言模型·github·模型蒸馏
陈童学哦1 小时前
DeepSeek Harness(Cordis):打破Agent框架黑盒,一切皆插件
人工智能
小睿科技1 小时前
建筑AI睿兔大脑 | AI把工程成本测算从经验活变成算清楚的技术活
人工智能
正经教主1 小时前
AI提示词工程(高阶)第19课:提示词评估与A/B测试
人工智能