0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-16 21:46:22 -05:00
astro/.changeset/tall-eyes-vanish.md
Bjorn Lu 73ec6f6c16
Implement custom client directives (#7074)
Co-authored-by: Sarah Rainsberger <sarah@rainsberger.ca>
2023-05-17 20:51:27 +08:00

1.2 KiB

astro
minor

Integrations can add new client: directives through the astro:config:setup hook's addClientDirective() API. To enable this API, the user needs to set experimental.customClientDirectives to true in their config.

import { defineConfig } from 'astro/config';
import onClickDirective from 'astro-click-directive';

export default defineConfig({
  integrations: [onClickDirective()],
  experimental: {
    customClientDirectives: true
  }
});
export default function onClickDirective() {
  return {
    hooks: {
      'astro:config:setup': ({ addClientDirective }) => {
        addClientDirective({
          name: 'click',
          entrypoint: 'astro-click-directive/click.js'
        });
      },
    }
  }
}
<Counter client:click />

The client directive file (e.g. astro-click-directive/click.js) should export a function of type ClientDirective:

import type { ClientDirective } from 'astro'

const clickDirective: ClientDirective = (load, opts, el) => {
  window.addEventListener('click', async () => {
    const hydrate = await load()
    await hydrate()
  }, { once: true })
}

export default clickDirective