Skip to content

addDts

addDts allows you to inject a .d.ts file into the user’s project. It will create a file inside .astro and reference it from src/env.d.ts. For example:

my-integration/index.ts
1
import {
2
defineIntegration,
3
addDts
4
} from "astro-integration-kit";
5
6
export default defineIntegration({
7
// ...
8
setup() {
9
return {
10
hooks: {
11
"astro:config:setup": (params) => {
12
addDts(params, {
13
name: "my-integration",
14
content: `declare module "virtual:my-integration" {}`
15
})
16
}
17
}
18
}
19
}
20
})

How to generate content?

Here are a few suggestions regarding how to deal with content conveniently.

Static content

If content is a static string and you want to have a nice DX instead of managing it inside a string, we recommend you use a stub approach:

my-integration/stubs/virtual-import.d.ts
1
declare module "virtual:my-integration" {}
my-integration/index.ts
1
import { defineIntegration, createResolver, addDts } from "astro-integration-kit";
2
import { readFileSync } from "node:fs";
3
4
export default defineIntegration({
5
// ...
6
setup() {
7
const { resolve } = createResolver(import.meta.url)
8
9
return {
10
hooks: {
11
"astro:config:setup": (params) => {
12
addDts(params, {
13
name: "my-integration",
14
content: readFileSync(resolve("./stubs/virtual-import.d.ts"), "utf-8")
15
})
16
}
17
}
18
}
19
}
20
})

Dynamic content

If you want to generate type from user data/input (codegen), you can go for interpolation or a buffer approach.

Interpolation

my-integration/index.ts
1
import { defineIntegration, addDts } from "astro-integration-kit";
2
import { z } from "astro/zod"
3
4
export default defineIntegration({
5
// ...
6
optionsSchema: z.object({ locales: z.array(z.string()) }),
7
setup({ options }) {
8
return {
9
hooks: {
10
"astro:config:setup": (params) => {
11
addDts(params, {
12
name: "my-integration",
13
content: `declare module "virtual:my-integration" {
14
export type Locale: ${options.locales.map(e => `"${e}"`).join(" | ")};
15
}`
16
})
17
}
18
}
19
}
20
}
21
})

Buffer

my-integration/index.ts
1
import { defineIntegration, addDts } from "astro-integration-kit";
2
import { z } from "astro/zod"
3
4
export default defineIntegration({
5
// ...
6
optionsSchema: z.object({ locales: z.array(z.string()) }),
7
setup({ options }) {
8
return {
9
hooks: {
10
"astro:config:setup": (params) => {
11
let content = `declare module "virtual:my-integration" {
12
export type Locale:`
13
for (const locale of locales) {
14
content += ` | ${locale}`
15
}
16
content += ";\n}"
17
18
addDts(params, {
19
name: "my-integration",
20
content
21
})
22
}
23
}
24
}
25
}
26
})