在 day-06 我們表列了很多 , client:* Directives , 說明 Astro 提供不同類型的 js hydrate 時機
複習一下有
其實還有一種 , 那就是今天要討論的 Custom Client Directives
下面定義一個 client:click - 元件在點擊後 hydrate
addClientDirective option
Section titled addClientDirective option
Added in: astro@2.6.0
Type: (directive: ClientDirectiveConfig ) => void;
Adds a custom client directive to be used in .astro files.
Note that directive entrypoints are only bundled through esbuild and should be kept small so they don’t slow down component hydration.
Example usage:
// ------- astro.config.mjs -------- //
import { defineConfig } from 'astro/config';
import clickDirective from './astro-click-directive/register.js'
// https://astro.build/config
export default defineConfig({
integrations: [
clickDirective()
],
});
// ------- astro-click-directive/register.js -------- //
/**
* @type {() => import('astro').AstroIntegration}
*/
export default () => ({
name: "client:click",
hooks: {
"astro:config:setup": ({ addClientDirective }) => {
addClientDirective({
name: "click",
entrypoint: "./astro-click-directive/click.js",
});
},
},
});
// ------- astro-click-directive/click.js -------- //
/**
* Hydrate on first click on the window
* @type {import('astro').ClientDirective}
*/
export default (load, opts, el) => {
window.addEventListener('click', async () => {
const hydrate = await load()
await hydrate()
}, { once: true })
}
You can also add types for the directives in your library’s type definition file:
// ------- astro-click-directive/index.d.ts -------- //
import 'astro'
declare module 'astro' {
interface AstroClientDirectives {
'client:click'?: boolean
}
}