API Reference
AlpineComponent
The core object for managing component registration and loading.
AlpineComponent.setBase(basePath)
Set the base URL path for component files.
| Parameter | Type | Description |
|---|---|---|
basePath | string | Base URL path. Default: /components |
// Example with Vite's base config
AlpineComponent.setBase(`${import.meta.env.BASE_URL}components`);AlpineComponent.register(name, templatePath, jsPath?, options?)
Register a component for use with x-component.
| Parameter | Type | Description |
|---|---|---|
name | string | Component name used in x-component="name" |
templatePath | string | Path to HTML template (relative to base or absolute) |
jsPath | string? | Optional path to JS module exporting Alpine data function |
options.eager | boolean? | If true, prefetch component immediately on registration |
// Template only
AlpineComponent.register('alert', 'alert/alert.html');
// Template + JS data
AlpineComponent.register('modal', 'modal/modal.html', 'modal/modal.js');
// Eagerly prefetch
AlpineComponent.register('header', 'header/header.html', null, { eager: true });x-component Directive
The Alpine directive for rendering components.
Basic Usage
<div x-component="componentName"></div>Modifiers
| Modifier | Description | Example |
|---|---|---|
.eager | Load immediately (default behavior) | x-component.eager="modal" |
.visible | Load when element enters viewport | x-component.visible="modal" |
.visible.{margin} | Load with IntersectionObserver rootMargin | x-component.visible.100px="modal" |
.event.{eventName} | Load when window receives event | x-component.event.openModal="modal" |
.event | Load on alpine-components:load when detail.id matches the component name | x-component.event="modal" |
Component JS Module
Component JS files should export a default function that returns an Alpine data object:
// modal.js
export default function modal(options = {}) {
return {
// Reactive state
isOpen: false,
// Computed properties as getters returning x-bind objects
get trigger() {
return {
'@click'() { this.isOpen = true }
};
},
// Methods
open() { this.isOpen = true },
close() { this.isOpen = false },
// Lifecycle
init() {
console.log('Component initialized');
},
destroy() {
console.log('Component destroyed');
}
};
}AlpineComponentPlugin
The Alpine.js plugin that provides the x-component directive.
import Alpine from 'alpinejs';
import { AlpineComponentPlugin } from 'alpine-components';
Alpine.plugin(AlpineComponentPlugin);
Alpine.start();The plugin must be registered before calling Alpine.start().