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
"astro:config:setup": (params) => {
11
addDts(params, {
12
name: "my-integration",
13
content: `declare module "virtual:my-integration" {}`
14
})
15
}
16
}
17
}
18
})

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
"astro:config:setup": (params) => {
11
addDts(params, {
12
name: "my-integration",
13
content: readFileSync(resolve("./stubs/virtual-import.d.ts"), "utf-8")
14
})
15
}
16
}
17
}
18
})

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
"astro:config:setup": (params) => {
10
addDts(params, {
11
name: "my-integration",
12
content: `declare module "virtual:my-integration" {
13
export type Locale: ${options.locales.map(e => `"${e}"`).join(" | ")};
14
}`
15
})
16
}
17
}
18
}
19
})

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
"astro:config:setup": (params) => {
10
let content = `declare module "virtual:my-integration" {
11
export type Locale:`
12
for (const locale of locales) {
13
content += ` | ${locale}`
14
}
15
content += ";\n}"
16
17
addDts(params, {
18
name: "my-integration",
19
content
20
})
21
}
22
}
23
}
24
})