如何创建和部署 Web Component
Web Components 是一套浏览器原生支持的组件化技术,允许创建可复用的自定义 HTML 元素。以下是完整指南:
一、创建 Web Component(4 步实现)
1 | // 1. 定义组件类(继承 HTMLElement) |
二、使用 Web Component
1 |
|
三、部署策略(3 种方式)
直接引入(快速部署)
1
2
3
4
5<!-- 本地文件 -->
<script src="path/to/my-component.js"></script>
<!-- CDN 托管 -->
<script src="https://cdn.example.com/my-component.js"></script>NPM 包发布(团队协作)
1
2
3# 发布步骤
npm init
npm publish --access public使用方安装:
1
npm install @yourname/my-component
导入使用:
1
import '@yourname/my-component';
HTML 模块化(现代浏览器)
1
2
3
4<script type="module">
import { MyComponent } from './my-component.js';
customElements.define('my-component', MyComponent);
</script>
四、最佳实践
- 命名规范:必须包含连字符(如
my-component
) - 响应式设计:在组件内使用 CSS 媒体查询
- 属性监听:
1
2
3
4
5
6
7static get observedAttributes() { return ['disabled']; }
attributeChangedCallback(name, oldVal, newVal) {
if (name === 'disabled') {
this.toggleAttribute('disabled', newVal !== null);
}
} - 浏览器兼容:添加 Web Components Polyfill(支持 IE11+)
五、完整生命周期
方法 | 触发时机 |
---|---|
constructor() |
元素创建时 |
connectedCallback() |
插入 DOM 时 |
disconnectedCallback() |
从 DOM 移除时 |
attributeChangedCallback() |
属性变化时 |
adoptedCallback() |
被移动到新文档时 |
六、示例:带属性的组件
1 | class ColorBlock extends HTMLElement { |
1 | <color-block color="#FF5733"></color-block> |
七、调试技巧
- 在 Chrome DevTools 中启用:
1
Settings → Experiments → 勾选 "Web Components"
- 直接检查 Shadow DOM:
1
document.querySelector('my-component').shadowRoot
通过以上步骤,您可以创建出企业级可复用的组件。实际案例参考:GitHub 官方 Web Components 示例库