definePlugin
Allows defining a type-safe plugin that can be used in defineIntegration
.
1import type { AstroConfig } from "astro";2import type { Plugin, PluginOption } from "vite";3import { definePlugin } from "astro-integration-kit";4import { hasVitePlugin, getPlugins } from "../utilities/has-vite-plugin.js";5
6export 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
:
1import { defineIntegration, withPlugins } from "astro-integration-kit";2import { hasVitePluginPlugin } from "astro-integration-kit/plugins";3
4export 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 asetup
function.1definePlugin({2name: "my-plugin",3setup() {4// ...5}6}) -
The
setup
function accepts a name and must return an object1definePlugin({2name: "my-plugin",3setup({ name }) {4return {}5}6}) -
The returned object is made of astro hooks and must returned an object of additional properties
1definePlugin({2name: "my-plugin",3setup({ name }) {4return {5"astro:config:setup": ({ updateConfig }) => ({6doSomething: (foo: string) => {7updateConfig({8// ...9})10}11})12}13}14})
Limitations
- 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!