Skip to content

defineUtility

Allows defining a type-safe function requiring all the params of a given hook.

package/src/utilities/inject-dev-route.ts
1
import type { InjectedRoute } from "astro";
2
import { defineUtility } from "astro-integration-kit";
3
4
export const injectDevRoute = defineUtility("astro:config:setup")(
5
({ command, injectRoute }, injectedRoute: InjectedRoute) => {
6
if (command === "dev") {
7
injectRoute(injectedRoute);
8
}
9
},
10
);

Usage

Even though the syntax looks a bit scary, it’s actually very simple!

  1. Call defineUtility with a hook name. That will be used to type the next steps:

    1
    import { defineUtility } from "astro-integration-kit";
    2
    3
    export const injectDevRoute = defineUtility("astro:config:setup")
  2. Using currying, call the returned function with the typed params:

    1
    import { defineUtility } from "astro-integration-kit";
    2
    3
    export const injectDevRoute = defineUtility("astro:config:setup")(
    4
    // Typed as HookParameters<"astro:config:setup">
    5
    (params) => {}
    6
    )
  3. (Optional) Add your own parameters:

    1
    import type { InjectedRoute } from "astro";
    2
    import { defineUtility } from "astro-integration-kit";
    3
    4
    export const injectDevRoute = defineUtility("astro:config:setup")(
    5
    (params, injectedRoute: InjectedRoute) => {}
    6
    )
  4. Implement the actual logic:

    1
    import type { InjectedRoute } from "astro";
    2
    import { defineUtility } from "astro-integration-kit";
    3
    4
    export const injectDevRoute = defineUtility("astro:config:setup")(
    5
    ({ command, injectRoute }, injectedRoute: InjectedRoute) => {
    6
    if (command === "dev") {
    7
    injectRoute(injectedRoute);
    8
    }
    9
    },
    10
    );
  5. Use the utility in your integration:

    1
    import { defineIntegration, createResolver, injectDevRoute } from "astro-integration-kit"
    2
    3
    export const integration = defineIntegration({
    4
    name: "my-integration",
    5
    setup() {
    6
    const { resolve } = createResolver(import.meta.url)
    7
    8
    return {
    9
    hooks: {
    10
    "astro:config:setup": (params) => {
    11
    injectDevRoute(params, {
    12
    pattern: "/",
    13
    entrypoint: resolve("./pages/index.astro")
    14
    })
    15
    }
    16
    }
    17
    }
    18
    }
    19
    })