Skip to content

definePlugin

Allows defining a type-safe plugin that can be used in defineIntegration.

package/plugins/has-vite-plugin.ts
1
import type { AstroConfig } from "astro";
2
import type { Plugin, PluginOption } from "vite";
3
import { definePlugin } from "astro-integration-kit";
4
import { hasVitePlugin, getPlugins } from "../utilities/has-vite-plugin.js";
5
6
export const hasVitePluginPlugin = definePlugin({
7
name: "hasVitePlugin",
8
setup() {
9
return {
10
"astro:config:setup": (params) => {
11
const currentPlugins = getPlugins(
12
new Set(),
13
params.config.vite?.plugins,
14
);
15
16
const { updateConfig, config } = params;
17
18
params.updateConfig = (newConfig) => {
19
config.vite.plugins = Array.from(
20
getPlugins(currentPlugins, newConfig.vite?.plugins),
21
);
22
return updateConfig(newConfig);
23
};
24
25
return {
26
hasVitePlugin: (plugin: string | PluginOption) =>
27
hasVitePlugin(params, {
28
plugin,
29
}),
30
};
31
},
32
};
33
},
34
});

You can then use it in withPlugins:

my-integration/index.ts
1
import { defineIntegration, withPlugins } from "astro-integration-kit";
2
import { hasVitePluginPlugin } from "astro-integration-kit/plugins";
3
4
export default defineIntegration({
5
name: "my-integration",
6
setup({ name }) {
7
return withPlugins({
8
name,
9
plugins: [hasVitePluginPlugin],
10
hooks: {
11
"astro:config:setup": ({ hasVitePlugin }) => {}
12
}
13
})
14
}
15
})

Usage

  • A plugin defines a name and a setup function.

    1
    definePlugin({
    2
    name: "my-plugin",
    3
    setup() {
    4
    // ...
    5
    }
    6
    })
  • The setup function accepts a name and must return an object

    1
    definePlugin({
    2
    name: "my-plugin",
    3
    setup({ name }) {
    4
    return {}
    5
    }
    6
    })
  • The returned object is made of astro hooks and must returned an object of additional properties

    1
    definePlugin({
    2
    name: "my-plugin",
    3
    setup({ name }) {
    4
    return {
    5
    "astro:config:setup": ({ updateConfig }) => ({
    6
    doSomething: (foo: string) => {
    7
    updateConfig({
    8
    // ...
    9
    })
    10
    }
    11
    })
    12
    }
    13
    }
    14
    })

Limitations

  1. Plugins support overrides. That means that if 2 plugins declare the same name, the latest will be kept.

Practical examples

Astro Integration Kit uses definePlugin for its core plugins under the hood, have a look at our source for practical examples!