API Reference

AlpineComponent

The core object for managing component registration and loading.

AlpineComponent.setBase(basePath)

Set the base URL path for component files.

ParameterTypeDescription
basePathstringBase 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.

ParameterTypeDescription
namestringComponent name used in x-component="name"
templatePathstringPath to HTML template (relative to base or absolute)
jsPathstring?Optional path to JS module exporting Alpine data function
options.eagerboolean?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

ModifierDescriptionExample
.eagerLoad immediately (default behavior)x-component.eager="modal"
.visibleLoad when element enters viewportx-component.visible="modal"
.visible.{margin}Load with IntersectionObserver rootMarginx-component.visible.100px="modal"
.event.{eventName}Load when window receives eventx-component.event.openModal="modal"
.eventLoad on alpine-components:load when detail.id matches the component namex-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().

Built with Alpine Components. GitHub ยท npm