addVirtualImports
addVirtualImports
allows you to create virtual modules and share data from your integration. For example:
import { defineIntegration } from "astro-integration-kit";import { addVirtualImportsPlugin } from "astro-integration-kit/plugins";
export default defineIntegration({ name: "my-integration", plugins: [addVirtualImportsPlugin], setup() { return { "astro:config:setup": ({ addVirtualImports }) => { addVirtualImports({ 'virtual:my-integration/config': `export default ${JSON.stringify({ foo: "bar" })}`, }) addVirtualImports([ { id: "virtual:my-integration/advanced", content: "export const foo = 'server'", context: "server" }, { id: "virtual:my-integration/advanced", content: "export const foo = 'client'", context: "client" }, ]) } } }})
import type { AstroIntegration } from "astro";import { addVirtualImports } from "astro-integration-kit/utilities";
export default function myIntegration(): AstroIntegration { return { name: "my-integration", hooks: { "astro:config:setup": ({ config, updateConfig }) => { addVirtualImports({ updateConfig, config, name: 'my-integration', imports: { 'virtual:my-integration/config': `export default ${JSON.stringify({ foo: "bar" })}`, }, }) addVirtualImports({ config, updateConfig, name: 'my-integration', imports: [ { id: "virtual:my-integration/advanced", content: "export const foo = 'server'", context: "server" }, { id: "virtual:my-integration/advanced", content: "export const foo = 'client'", context: "client" }, ] }) } } }}
You can now access the config somewhere else, for example inside a page injected by your integration:
---import config from "virtual:my-integration/config",
console.log(config.foo) // "bar"---
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:
declare module "virtual:my-integration/config" { export default { foo: string };}