Skip to content

addVirtualImports

addVirtualImports allows you to create virtual modules and share data from your integration. For example:

my-integration/index.ts
1
import {
2
defineIntegration,
3
addVirtualImports
4
} from "astro-integration-kit";
5
6
export default defineIntegration({
7
// ...
8
setup({ name }) {
9
return {
10
hooks: {
11
"astro:config:setup": (params) => {
12
addVirtualImports(params, {
13
name,
14
imports: {
15
'virtual:my-integration/config': `export default ${JSON.stringify({ foo: "bar" })}`,
16
}
17
})
18
19
addVirtualImports(params, {
20
name,
21
imports: [
22
{
23
id: "virtual:my-integration/advanced",
24
content: "export const foo = 'server'",
25
context: "server"
26
},
27
{
28
id: "virtual:my-integration/advanced",
29
content: "export const foo = 'client'",
30
context: "client"
31
},
32
]
33
})
34
}
35
}
36
}
37
}
38
})

You can now access the config somewhere else, for example inside a page injected by your integration:

my-integration/src/pages/index.astro
1
---
2
import config from "virtual:my-integration/config",
3
4
console.log(config.foo) // "bar"
5
---

Typing your virtual module

In order to get the types for your virtual modules while developing your integration, you’ll need to manually declare a virtual module.

First create a virtual.d.ts file in your integration root. Then you can define your virtual modules as global TypeScript modules:

my-integration/virtual.d.ts
1
declare module "virtual:my-integration/config" {
2
export default { foo: string };
3
}