@duskmoon-dev/el-base

中文文档
1.10.3发布于 2026/11/11TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 8612

Core utilities and base classes for DuskMoon custom elements.

原始使用文档
文档目录12 节
  1. Installation
  2. Usage
  3. BaseElement
  4. CSS Utilities
  5. Default Theme
  6. API
  7. BaseElement
  8. Property Definitions
  9. Lifecycle
  10. TypeScript Types
  11. Creating Custom Elements
  12. License

@duskmoon-dev/el-base

Core utilities and base classes for DuskMoon custom elements.

Installation

bun add @duskmoon-dev/el-base

Usage

BaseElement

The BaseElement class provides a foundation for creating custom elements with:

  • Shadow DOM setup with adoptedStyleSheets
  • Reactive properties with attribute reflection
  • Batched updates using microtask queue
  • Style injection utilities
  • Event emission helpers
import { BaseElement, css } from '@duskmoon-dev/el-base';

const styles = css`
  :host {
    display: block;
  }
  .greeting {
    color: var(--dm-primary);
  }
`;

class MyGreeting extends BaseElement {
  static properties = {
    name: { type: String, reflect: true, default: 'World' },
  };

  declare name: string;

  constructor() {
    super();
    this.attachStyles(styles);
  }

  render() {
    return `<div class="greeting">Hello, ${this.name}!</div>`;
  }
}

customElements.define('my-greeting', MyGreeting);

CSS Utilities

css Template Tag

Creates a CSSStyleSheet from a template literal:

import { css } from '@duskmoon-dev/el-base';

const styles = css`
  :host {
    display: inline-flex;
  }
  button {
    padding: 0.5rem 1rem;
  }
`;

combineStyles

Combines multiple stylesheets:

import { combineStyles } from '@duskmoon-dev/el-base';

const combinedStyles = combineStyles(baseStyles, themeStyles, componentStyles);

cssVars

Creates CSS custom property declarations:

import { cssVars } from '@duskmoon-dev/el-base';

const vars = cssVars({
  'dm-primary': '#3b82f6',
  'dm-spacing': '1rem',
});
// Returns: '--dm-primary: #3b82f6; --dm-spacing: 1rem;'

Default Theme

The package includes default CSS custom properties for theming. Import the theme stylesheet:

import { defaultTheme, resetStyles } from '@duskmoon-dev/el-base';

// Apply to shadow root
this.shadowRoot.adoptedStyleSheets = [resetStyles, defaultTheme, componentStyles];

Color Tokens

VariableDescription
--dm-primaryPrimary brand color
--dm-secondarySecondary color
--dm-successSuccess/positive color
--dm-warningWarning color
--dm-errorError/danger color
--dm-infoInformation color

Gray Scale

VariableDescription
--dm-gray-50Lightest gray
--dm-gray-100 through --dm-gray-800Gray scale
--dm-gray-900Darkest gray

Typography

VariableDescription
--dm-font-familyBase font family
--dm-font-size-xs through --dm-font-size-2xlFont sizes
--dm-font-weight-normal, --dm-font-weight-medium, --dm-font-weight-semibold, --dm-font-weight-boldFont weights
--dm-line-height-tight, --dm-line-height-normal, --dm-line-height-relaxedLine heights

Spacing

VariableDescription
--dm-spacing-xsExtra small (0.25rem)
--dm-spacing-smSmall (0.5rem)
--dm-spacing-mdMedium (1rem)
--dm-spacing-lgLarge (1.5rem)
--dm-spacing-xlExtra large (2rem)

Border Radius

VariableDescription
--dm-radius-smSmall radius
--dm-radius-mdMedium radius
--dm-radius-lgLarge radius
--dm-radius-fullFull/pill radius

Shadows

VariableDescription
--dm-shadow-smSmall shadow
--dm-shadow-mdMedium shadow
--dm-shadow-lgLarge shadow

Transitions

VariableDescription
--dm-transition-fastFast transition (150ms)
--dm-transition-normalNormal transition (200ms)
--dm-transition-slowSlow transition (300ms)

API

BaseElement

MethodDescription
attachStyles(styles)Attach one or more stylesheets to Shadow DOM
render()Override to return HTML content string
update()Called when reactive properties change (batched)
emit(name, detail?)Emit a CustomEvent from the element
query(selector)Query single element in Shadow DOM
queryAll(selector)Query all matching elements in Shadow DOM

Property Definitions

Define reactive properties with automatic attribute reflection:

static properties = {
  // Simple string property
  label: { type: String },

  // Boolean with attribute reflection
  disabled: { type: Boolean, reflect: true },

  // Number with default value
  count: { type: Number, default: 0 },

  // Custom attribute name (kebab-case)
  maxItems: { type: Number, attribute: 'max-items' },

  // Object/Array (not reflected to attributes)
  data: { type: Object },
  items: { type: Array, default: [] },
};

Property definition options:

OptionTypeDescription
typeFunctionType constructor: String, Number, Boolean, Object, Array
reflectbooleanWhether to reflect property to attribute
attributestringCustom attribute name (defaults to lowercase property name)
defaultanyDefault value for the property

Lifecycle

class MyElement extends BaseElement {
  // Called when element is added to DOM
  connectedCallback() {
    super.connectedCallback();
    // Setup code
  }

  // Called when element is removed from DOM
  disconnectedCallback() {
    super.disconnectedCallback();
    // Cleanup code
  }

  // Called when properties change (batched)
  update() {
    // Re-render or update DOM
    this.shadowRoot.innerHTML = this.render();
  }

  // Return HTML string for Shadow DOM content
  render() {
    return `<div>Content</div>`;
  }
}

TypeScript Types

import type {
  PropertyDefinition,
  PropertyDefinitions,
  Size,
  Variant,
  ValidationState,
  BaseElementProps,
  SizableProps,
  VariantProps,
  FormElementProps,
  ValidatableProps,
  ValueChangeEventDetail,
} from '@duskmoon-dev/el-base';

Creating Custom Elements

Full example of a custom element:

import { BaseElement, css, defaultTheme, resetStyles } from '@duskmoon-dev/el-base';

const styles = css`
  :host {
    display: inline-block;
  }

  .counter {
    display: flex;
    align-items: center;
    gap: var(--dm-spacing-sm);
  }

  button {
    padding: var(--dm-spacing-xs) var(--dm-spacing-sm);
    border-radius: var(--dm-radius-sm);
    background: var(--dm-primary);
    color: white;
    border: none;
    cursor: pointer;
    transition: opacity var(--dm-transition-fast);
  }

  button:hover {
    opacity: 0.9;
  }

  .value {
    min-width: 2rem;
    text-align: center;
    font-weight: var(--dm-font-weight-medium);
  }
`;

export class MyCounter extends BaseElement {
  static properties = {
    value: { type: Number, reflect: true, default: 0 },
    min: { type: Number, default: 0 },
    max: { type: Number, default: 100 },
  };

  declare value: number;
  declare min: number;
  declare max: number;

  constructor() {
    super();
    this.attachStyles(resetStyles, defaultTheme, styles);
  }

  connectedCallback() {
    super.connectedCallback();
    this.shadowRoot?.addEventListener('click', this.handleClick.bind(this));
  }

  private handleClick(e: Event) {
    const target = e.target as HTMLElement;
    if (target.matches('[data-action="decrement"]')) {
      this.decrement();
    } else if (target.matches('[data-action="increment"]')) {
      this.increment();
    }
  }

  private decrement() {
    if (this.value > this.min) {
      this.value--;
      this.emit('change', { value: this.value });
    }
  }

  private increment() {
    if (this.value < this.max) {
      this.value++;
      this.emit('change', { value: this.value });
    }
  }

  render() {
    return `
      <div class="counter">
        <button data-action="decrement" ${this.value <= this.min ? 'disabled' : ''}>-</button>
        <span class="value">${this.value}</span>
        <button data-action="increment" ${this.value >= this.max ? 'disabled' : ''}>+</button>
      </div>
    `;
  }
}

export function register() {
  if (!customElements.get('my-counter')) {
    customElements.define('my-counter', MyCounter);
  }
}

License

MIT

版本与发布记录

@duskmoon-dev/el-base 共发布 49 个版本,首次发布于 2026/02/21;过去 12 个月发布了 49 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.10.3latest2026/11/112 天前
1.10.22026/10/2222 天前
1.10.12026/10/1627 天前
1.10.02026/10/1628 天前
1.9.32026/10/131 个月前
1.9.22026/10/131 个月前

关于 @duskmoon-dev/el-base 的常见问题

@duskmoon-dev/el-base 是什么?

Core utilities and base classes for DuskMoon custom elements.

如何安装 @duskmoon-dev/el-base?

在项目目录运行 npm install @duskmoon-dev/el-base,或使用 pnpm add / yarn add / bun add。

@duskmoon-dev/el-base 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@duskmoon-dev/el-base 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@duskmoon-dev/el-base 可以商用吗?

@duskmoon-dev/el-base 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@duskmoon-dev/el-base 的下载量有多少?

根据 npm 官方下载统计,@duskmoon-dev/el-base 在 2026/10/13 – 2026/11/11 这 30 天内被下载 8,612 次,日均约 287 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@duskmoon-dev/el-base 还在维护吗?

最新版本 1.10.3 发布于 2026/11/11(2 天前);至今共发布 49 个版本,其中过去 12 个月发布了 49 个;首次发布于 2026/02/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。