KC's Workspace
    Preparing search index...

    There are two types of plugins in Vite. App plugins and environment plugins. Environment Plugins are defined by a constructor function that will be called once per each environment allowing users to have completely different plugins for each of them. The constructor gets the resolved environment after the server and builder has already been created simplifying config access and cache management for environment specific plugins. Environment Plugins are closer to regular rollup plugins. They can't define app level hooks (like config, configResolved, configureServer, etc).

    interface Plugin<A = any> {
        api?: A;
        apply?:
            | "build"
            | "serve"
            | ((this: void, config: UserConfig, env: ConfigEnv) => boolean);
        applyToEnvironment?: (
            environment: PartialEnvironment,
        ) => true | PluginOption | Promise<boolean>;
        augmentChunkHash?: ObjectHook<
            (this: PluginContext, chunk: RenderedChunk) => string | void,
            {},
        >;
        banner?: ObjectHook<AddonHook, {}>;
        buildApp?: ObjectHook<BuildAppHook>;
        buildEnd?: ObjectHook<
            (
                this: PluginContext,
                ...parameters: [err?: Error],
            ) => void | Promise<void>,
            { sequential?: boolean },
        >;
        buildStart?: ObjectHook<
            (
                this: PluginContext,
                ...parameters: [options: NormalizedInputOptions],
            ) => void | Promise<void>,
            { sequential?: boolean },
        >;
        closeBundle?: ObjectHook<
            (
                this: PluginContext,
                ...parameters: [error?: Error],
            ) => void | Promise<void>,
            { sequential?: boolean },
        >;
        closeWatcher?: ObjectHook<
            (this: PluginContext, ...parameters: []) => void | Promise<void>,
            { sequential?: boolean },
        >;
        config?: ObjectHook<
            (
                this: ConfigPluginContext,
                config: UserConfig,
                env: ConfigEnv,
            ) =>
                | void
                | Omit<UserConfig, "plugins">
                | Promise<void | Omit<UserConfig, "plugins"> | null>
                | null,
        >;
        configEnvironment?: ObjectHook<
            (
                this: ConfigPluginContext,
                name: string,
                config: EnvironmentOptions,
                env: ConfigEnv & { isSsrTargetWebworker?: boolean },
            ) =>
                | void
                | EnvironmentOptions
                | Promise<void | EnvironmentOptions | null>
                | null,
        >;
        configResolved?: ObjectHook<
            (
                this: MinimalPluginContextWithoutEnvironment,
                config: ResolvedConfig,
            ) => void | Promise<void>,
        >;
        configurePreviewServer?: ObjectHook<PreviewServerHook>;
        configureServer?: ObjectHook<ServerHook>;
        enforce?: "pre" | "post";
        footer?: ObjectHook<AddonHook, {}>;
        generateBundle?: ObjectHook<
            (
                this: PluginContext,
                ...parameters: [
                    outputOptions: NormalizedOutputOptions,
                    bundle: OutputBundle,
                    isWrite: boolean,
                ],
            ) => void
            | Promise<void>,
            {},
        >;
        handleHotUpdate?: ObjectHook<
            (
                this: MinimalPluginContextWithoutEnvironment,
                ctx: HmrContext,
            ) => void | ModuleNode[] | Promise<void | ModuleNode[]>,
        >;
        hotUpdate?: ObjectHook<
            (
                this: MinimalPluginContext & { environment: DevEnvironment },
                options: HotUpdateOptions,
            ) =>
                | void
                | EnvironmentModuleNode[]
                | Promise<void | EnvironmentModuleNode[]>,
        >;
        intro?: ObjectHook<AddonHook, {}>;
        load?: ObjectHook<
            (
                this: PluginContext,
                id: string,
                options?: { ssr?: boolean },
            ) => LoadResult | Promise<LoadResult>,
            { filter?: { id?: StringFilter<string | RegExp> | undefined } },
        >;
        meta?: PluginMeta;
        moduleParsed?: ObjectHook<
            (
                this: PluginContext,
                ...parameters: [moduleInfo: ModuleInfo],
            ) => void | Promise<void>,
            { sequential?: boolean },
        >;
        name: string;
        onLog?: ObjectHook<
            (
                this: MinimalPluginContext,
                level: "debug" | "warn" | "info",
                log: RolldownLog,
            ) => boolean | NullValue<void>,
            {},
        >;
        options?: ObjectHook<
            (
                this: MinimalPluginContext,
                ...parameters: [options: InputOptions],
            ) => InputOptions | NullValue<void> | Promise<InputOptions | NullValue<void>>,
            {},
        >;
        outputOptions?: ObjectHook<
            (
                this: MinimalPluginContext,
                options: OutputOptions,
            ) => OutputOptions | NullValue<void>,
            {},
        >;
        outro?: ObjectHook<AddonHook, {}>;
        perEnvironmentStartEndDuringDev?: boolean;
        perEnvironmentWatchChangeDuringDev?: boolean;
        renderChunk?: ObjectHook<
            (
                this: PluginContext,
                ...parameters: [
                    code: string,
                    chunk: RenderedChunk,
                    outputOptions: NormalizedOutputOptions,
                    meta: RenderedChunkMeta,
                ],
            ) => string | NullValue<void> | RolldownMagicString | { code: string | RolldownMagicString; map?: SourceMapInput; } | Promise<string | NullValue<void> | RolldownMagicString | { code: string | RolldownMagicString; map?: SourceMapInput; }>,
            { filter?: Pick<HookFilter, "code">
            | TopLevelFilterExpression[] },
        >;
        renderError?: ObjectHook<
            (
                this: PluginContext,
                ...parameters: [error: Error],
            ) => void | Promise<void>,
            { sequential?: boolean },
        >;
        renderStart?: ObjectHook<
            (
                this: PluginContext,
                ...parameters: [
                    outputOptions: NormalizedOutputOptions,
                    inputOptions: NormalizedInputOptions,
                ],
            ) => void
            | Promise<void>,
            { sequential?: boolean },
        >;
        resolveDynamicImport?: ObjectHook<
            (
                this: PluginContext,
                ...parameters: [source: string, importer: string],
            ) => ResolveIdResult | Promise<ResolveIdResult>,
            {},
        >;
        resolveId?: ObjectHook<
            (
                this: PluginContext,
                source: string,
                importer: string | undefined,
                options: {
                    custom?: CustomPluginOptions;
                    isEntry: boolean;
                    kind?:
                        | "import-statement"
                        | "dynamic-import"
                        | "require-call"
                        | "import-rule"
                        | "url-token"
                        | "new-url"
                        | "hot-accept";
                    ssr?: boolean;
                },
            ) => ResolveIdResult | Promise<ResolveIdResult>,
            { filter?: { id?: StringFilter<RegExp> | undefined } },
        >;
        sharedDuringBuild?: boolean;
        shouldTransformCachedModule?: ObjectHook<
            (
                this: PluginContext,
                options: {
                    code: string;
                    id: string;
                    meta: CustomPluginOptions;
                    moduleSideEffects: boolean | "no-treeshake";
                },
            ) => boolean
            | void
            | null,
        >;
        transform?: ObjectHook<
            (
                this: TransformPluginContext,
                code: string,
                id: string,
                options?: { moduleType: ModuleType; ssr?: boolean },
            ) => TransformResult | Promise<TransformResult>,
            {
                filter?: {
                    code?: StringFilter<string | RegExp> | undefined;
                    id?: StringFilter<string | RegExp> | undefined;
                    moduleType?: ModuleTypeFilter | undefined;
                };
            },
        >;
        transformIndexHtml?: IndexHtmlTransform;
        version?: string;
        watchChange?: ObjectHook<
            (
                this: PluginContext,
                ...parameters: [id: string, event: { event: ChangeEvent }],
            ) => void | Promise<void>,
            { sequential?: boolean },
        >;
        writeBundle?: ObjectHook<
            (
                this: PluginContext,
                ...parameters: [
                    outputOptions: NormalizedOutputOptions,
                    bundle: OutputBundle,
                ],
            ) => void
            | Promise<void>,
            { sequential?: boolean },
        >;
    }

    Type Parameters

    • A = any

    Hierarchy (View Summary)

    Index
    api?: A

    Used for inter-plugin communication.

    apply?:
        | "build"
        | "serve"
        | ((this: void, config: UserConfig, env: ConfigEnv) => boolean)

    Apply the plugin only for serve or build, or on certain conditions.

    applyToEnvironment?: (
        environment: PartialEnvironment,
    ) => true | PluginOption | Promise<boolean>

    Define environments where this plugin should be active By default, the plugin is active in all environments

    Build Environments

    config?: ObjectHook<
        (
            this: ConfigPluginContext,
            config: UserConfig,
            env: ConfigEnv,
        ) =>
            | void
            | Omit<UserConfig, "plugins">
            | Promise<void | Omit<UserConfig, "plugins"> | null>
            | null,
    >

    Modify vite config before it's resolved. The hook can either mutate the passed-in config directly, or return a partial config object that will be deeply merged into existing config.

    Note: User plugins are resolved before running this hook so injecting other plugins inside the config hook will have no effect.

    configEnvironment?: ObjectHook<
        (
            this: ConfigPluginContext,
            name: string,
            config: EnvironmentOptions,
            env: ConfigEnv & { isSsrTargetWebworker?: boolean },
        ) =>
            | void
            | EnvironmentOptions
            | Promise<void | EnvironmentOptions | null>
            | null,
    >

    Modify environment configs before it's resolved. The hook can either mutate the passed-in environment config directly, or return a partial config object that will be deeply merged into existing config. This hook is called for each environment with a partially resolved environment config that already accounts for the default environment config values set at the root level. If plugins need to modify the config of a given environment, they should do it in this hook instead of the config hook. Leaving the config hook only for modifying the root default environment config.

    configResolved?: ObjectHook<
        (
            this: MinimalPluginContextWithoutEnvironment,
            config: ResolvedConfig,
        ) => void | Promise<void>,
    >

    Use this hook to read and store the final resolved vite config.

    configurePreviewServer?: ObjectHook<PreviewServerHook>

    Configure the preview server. The hook receives the PreviewServer instance. This can also be used to store a reference to the server for use in other hooks.

    The hooks are called before other middlewares are applied. A hook can return a post hook that will be called after other middlewares are applied. Hooks can be async functions and will be called in series.

    configureServer?: ObjectHook<ServerHook>

    Configure the vite server. The hook receives the ViteDevServer instance. This can also be used to store a reference to the server for use in other hooks.

    The hooks will be called before internal middlewares are applied. A hook can return a post hook that will be called after internal middlewares are applied. Hook can be async functions and will be called in series.

    enforce?: "pre" | "post"

    Enforce plugin invocation tier similar to webpack loaders. Hooks ordering is still subject to the order property in the hook object.

    Plugin invocation order:

    • alias resolution
    • enforce: 'pre' plugins
    • vite core plugins
    • normal plugins
    • vite build plugins
    • enforce: 'post' plugins
    • vite build post plugins
    handleHotUpdate?: ObjectHook<
        (
            this: MinimalPluginContextWithoutEnvironment,
            ctx: HmrContext,
        ) => void | ModuleNode[] | Promise<void | ModuleNode[]>,
    >

    Perform custom handling of HMR updates. The handler receives a context containing changed filename, timestamp, a list of modules affected by the file change, and the dev server instance.

    • The hook can return a filtered list of modules to narrow down the update. e.g. for a Vue SFC, we can narrow down the part to update by comparing the descriptors.

    • The hook can also return an empty array and then perform custom updates by sending a custom hmr payload via server.ws.send().

    • If the hook doesn't return a value, the hmr update will be performed as normal.

    hotUpdate?: ObjectHook<
        (
            this: MinimalPluginContext & { environment: DevEnvironment },
            options: HotUpdateOptions,
        ) =>
            | void
            | EnvironmentModuleNode[]
            | Promise<void | EnvironmentModuleNode[]>,
    >

    Perform custom handling of HMR updates. The handler receives an options containing changed filename, timestamp, a list of modules affected by the file change, and the dev server instance.

    • The hook can return a filtered list of modules to narrow down the update. e.g. for a Vue SFC, we can narrow down the part to update by comparing the descriptors.

    • The hook can also return an empty array and then perform custom updates by sending a custom hmr payload via environment.hot.send().

    • If the hook doesn't return a value, the hmr update will be performed as normal.

    meta?: PluginMeta

    Descriptive metadata about the plugin, such as the npm package it ships in.

    This does not affect bundling; it is informational and intended to be surfaced by tooling that inspects a build. See PluginMeta.

    name: string

    The name of the plugin, for use in error messages and logs.

    perEnvironmentStartEndDuringDev?: boolean

    Opt-in this plugin into per-environment buildStart and buildEnd during dev. For backward-compatibility, the buildStart hook is called only once during dev, for the client environment. Plugins can opt-in to be called per-environment, aligning with the build hook behavior.

    perEnvironmentWatchChangeDuringDev?: boolean

    Opt-in this plugin into per-environment watchChange during dev. For backward-compatibility, the watchChange hook is called only once during dev, for the client environment. Plugins can opt-in to be called per-environment, aligning with the watchChange hook behavior.

    resolveId?: ObjectHook<
        (
            this: PluginContext,
            source: string,
            importer: string | undefined,
            options: {
                custom?: CustomPluginOptions;
                isEntry: boolean;
                kind?:
                    | "import-statement"
                    | "dynamic-import"
                    | "require-call"
                    | "import-rule"
                    | "url-token"
                    | "new-url"
                    | "hot-accept";
                ssr?: boolean;
            },
        ) => ResolveIdResult | Promise<ResolveIdResult>,
        { filter?: { id?: StringFilter<RegExp> | undefined } },
    >

    extend hooks with ssr flag

    sharedDuringBuild?: boolean

    Opt-in this plugin into the shared plugins pipeline. For backward-compatibility, plugins are re-recreated for each environment during vite build --app We have an opt-in per plugin, and a general builder.sharedPlugins In a future major, we'll flip the default to be shared by default

    shouldTransformCachedModule?: ObjectHook<
        (
            this: PluginContext,
            options: {
                code: string;
                id: string;
                meta: CustomPluginOptions;
                moduleSideEffects: boolean | "no-treeshake";
            },
        ) => boolean
        | void
        | null,
    >

    This hook is not supported by Rolldown yet. But the type is declared for compatibility.

    This hook is not deprecated. It is marked as deprecated just to make it clear that this hook is currently a no-op.

    transformIndexHtml?: IndexHtmlTransform

    Transform index.html. The hook receives the following arguments:

    • html: string
    • ctx: IndexHtmlTransformContext, which contains:
      • path: public path when served
      • filename: filename on disk
      • server?: ViteDevServer (only present during serve)
      • bundle?: rollup.OutputBundle (only present during build)
      • chunk?: rollup.OutputChunk
      • originalUrl?: string

    It can either return a transformed string, or a list of html tag descriptors that will be injected into the <head> or <body>.

    By default the transform is applied after vite's internal html transform. If you need to apply the transform before vite, use an object: { order: 'pre', handler: hook }

    version?: string

    The version of the plugin, for use in inter-plugin communication scenarios.

    buildEnd?: ObjectHook<
        (
            this: PluginContext,
            ...parameters: [err?: Error],
        ) => void | Promise<void>,
        { sequential?: boolean },
    >

    Called when Rolldown has finished bundling, but before Output Generation Hooks. If an error occurred during the build, it is passed on to this hook.

    buildStart?: ObjectHook<
        (
            this: PluginContext,
            ...parameters: [options: NormalizedInputOptions],
        ) => void | Promise<void>,
        { sequential?: boolean },
    >

    Called on each rolldown | rolldown() build.

    This is the recommended hook to use when you need access to the options passed to rolldown | rolldown() as it takes the transformations by all options hooks into account and also contains the right default values for unset options.

    closeWatcher?: ObjectHook<
        (this: PluginContext, ...parameters: []) => void | Promise<void>,
        { sequential?: boolean },
    >

    Notifies a plugin when the watcher process will close so that all open resources can be closed too.

    This hook cannot be used by output plugins.

    load?: ObjectHook<
        (
            this: PluginContext,
            id: string,
            options?: { ssr?: boolean },
        ) => LoadResult | Promise<LoadResult>,
        { filter?: { id?: StringFilter<string | RegExp> | undefined } },
    >

    Defines a custom loader.

    Returning null defers to other load hooks or the built-in loading mechanism.

    You can use this.getModuleInfo() to find out the previous values of meta, moduleSideEffects inside this hook.

    moduleParsed?: ObjectHook<
        (
            this: PluginContext,
            ...parameters: [moduleInfo: ModuleInfo],
        ) => void | Promise<void>,
        { sequential?: boolean },
    >

    This hook is called each time a module has been fully parsed by Rolldown.

    This hook will wait until all imports are resolved so that the information in moduleInfo.importedIds, moduleInfo.dynamicallyImportedIds are complete and accurate. Note however that information about importing modules may be incomplete as additional importers could be discovered later. If you need this information, use the buildEnd hook.

    onLog?: ObjectHook<
        (
            this: MinimalPluginContext,
            level: "debug" | "warn" | "info",
            log: RolldownLog,
        ) => boolean | NullValue<void>,
        {},
    >

    A function that receives and filters logs and warnings generated by Rolldown and plugins before they are passed to the onLog option or printed to the console.

    If false is returned, the log will be filtered out. Otherwise, the log will be handed to the onLog hook of the next plugin, the onLog option, or printed to the console. Plugins can also change the log level of a log or turn a log into an error by passing the log object to this.error, this.warn, this.info or this.debug and returning false.

    options?: ObjectHook<
        (
            this: MinimalPluginContext,
            ...parameters: [options: InputOptions],
        ) => InputOptions | NullValue<void> | Promise<InputOptions | NullValue<void>>,
        {},
    >

    Replaces or manipulates the options object passed to rolldown | rolldown().

    Returning null does not replace anything.

    If you just need to read the options, it is recommended to use the buildStart hook as that hook has access to the options after the transformations from all options hooks have been taken into account.

    outputOptions?: ObjectHook<
        (
            this: MinimalPluginContext,
            options: OutputOptions,
        ) => OutputOptions | NullValue<void>,
        {},
    >

    Replaces or manipulates the output options object passed to RolldownBuild.generate | bundle.generate() or RolldownBuild.write | bundle.write().

    Returning null does not replace anything.

    If you just need to read the output options, it is recommended to use the renderStart hook as this hook has access to the output options after the transformations from all outputOptions hooks have been taken into account.

    resolveDynamicImport?: ObjectHook<
        (
            this: PluginContext,
            ...parameters: [source: string, importer: string],
        ) => ResolveIdResult | Promise<ResolveIdResult>,
        {},
    >

    Defines a custom resolver for dynamic imports.

    This hook exists only for Rollup compatibility. Please use resolveId instead.

    transform?: ObjectHook<
        (
            this: TransformPluginContext,
            code: string,
            id: string,
            options?: { moduleType: ModuleType; ssr?: boolean },
        ) => TransformResult | Promise<TransformResult>,
        {
            filter?: {
                code?: StringFilter<string | RegExp> | undefined;
                id?: StringFilter<string | RegExp> | undefined;
                moduleType?: ModuleTypeFilter | undefined;
            };
        },
    >

    Can be used to transform individual modules.

    Note that it's possible to return only properties and no code transformations.

    You can use this.getModuleInfo() to find out the previous values of meta, moduleSideEffects inside this hook.

    watchChange?: ObjectHook<
        (
            this: PluginContext,
            ...parameters: [id: string, event: { event: ChangeEvent }],
        ) => void | Promise<void>,
        { sequential?: boolean },
    >

    Notifies a plugin whenever Rolldown has detected a change to a monitored file in watch mode.

    If a build is currently running, this hook is called once the build finished. It will be called once for every file that changed.

    This hook cannot be used by output plugins.

    If you need to be notified immediately when a file changed, you can use the watch.onInvalidate option.

    augmentChunkHash?: ObjectHook<
        (this: PluginContext, chunk: RenderedChunk) => string | void,
        {},
    >

    Can be used to augment the hash of individual chunks. Called for each Rolldown output chunk.

    Returning a falsy value will not modify the hash. Truthy values will be used as an additional source for hash calculation.

    banner?: ObjectHook<AddonHook, {}>

    A hook equivalent to output.banner option.

    closeBundle?: ObjectHook<
        (
            this: PluginContext,
            ...parameters: [error?: Error],
        ) => void | Promise<void>,
        { sequential?: boolean },
    >

    Can be used to clean up any external service that may be running.

    Rolldown's CLI will make sure this hook is called after each run, but it is the responsibility of users of the JavaScript API to manually call RolldownBuild.close | bundle.close() once they are done generating bundles. For that reason, any plugin relying on this feature should carefully mention this in its documentation.

    If a plugin wants to retain resources across builds in watch mode, they can check for PluginContextMeta.watchMode | this.meta.watchMode in this hook and perform the necessary cleanup for watch mode in closeWatcher.

    footer?: ObjectHook<AddonHook, {}>

    A hook equivalent to output.footer option.

    generateBundle?: ObjectHook<
        (
            this: PluginContext,
            ...parameters: [
                outputOptions: NormalizedOutputOptions,
                bundle: OutputBundle,
                isWrite: boolean,
            ],
        ) => void
        | Promise<void>,
        {},
    >

    Called at the end of RolldownBuild.generate | bundle.generate() or immediately before the files are written in RolldownBuild.write | bundle.write().

    To modify the files after they have been written, use the writeBundle hook.

    intro?: ObjectHook<AddonHook, {}>

    A hook equivalent to output.intro option.

    outro?: ObjectHook<AddonHook, {}>

    A hook equivalent to output.outro option.

    renderChunk?: ObjectHook<
        (
            this: PluginContext,
            ...parameters: [
                code: string,
                chunk: RenderedChunk,
                outputOptions: NormalizedOutputOptions,
                meta: RenderedChunkMeta,
            ],
        ) => string | NullValue<void> | RolldownMagicString | { code: string | RolldownMagicString; map?: SourceMapInput; } | Promise<string | NullValue<void> | RolldownMagicString | { code: string | RolldownMagicString; map?: SourceMapInput; }>,
        { filter?: Pick<HookFilter, "code">
        | TopLevelFilterExpression[] },
    >

    Can be used to transform individual chunks. Called for each Rolldown output chunk file.

    Returning null will apply no transformations. If you change code in this hook and want to support source maps, you need to return a map describing your changes, see Source Code Transformations section.

    chunk is mutable and changes applied in this hook will propagate to other plugins and to the generated bundle. That means if you add or remove imports or exports in this hook, you should update RenderedChunk.imports | imports, RenderedChunk.importedBindings | importedBindings and/or RenderedChunk.exports | exports accordingly.

    renderError?: ObjectHook<
        (
            this: PluginContext,
            ...parameters: [error: Error],
        ) => void | Promise<void>,
        { sequential?: boolean },
    >

    Called when Rolldown encounters an error during RolldownBuild.generate | bundle.generate() or RolldownBuild.write | bundle.write().

    To get notified when generation completes successfully, use the generateBundle hook.

    renderStart?: ObjectHook<
        (
            this: PluginContext,
            ...parameters: [
                outputOptions: NormalizedOutputOptions,
                inputOptions: NormalizedInputOptions,
            ],
        ) => void
        | Promise<void>,
        { sequential?: boolean },
    >

    Called initially each time RolldownBuild.generate | bundle.generate() or RolldownBuild.write | bundle.write() is called.

    To get notified when generation has completed, use the generateBundle and renderError hooks.

    This is the recommended hook to use when you need access to the output options passed to RolldownBuild.generate | bundle.generate() or RolldownBuild.write | bundle.write() as it takes the transformations by all outputOptions hooks into account and also contains the right default values for unset options.

    It also receives the input options passed to rolldown | rolldown() so that plugins that can be used as output plugins, i.e. plugins that only use generate phase hooks, can get access to them.

    writeBundle?: ObjectHook<
        (
            this: PluginContext,
            ...parameters: [
                outputOptions: NormalizedOutputOptions,
                bundle: OutputBundle,
            ],
        ) => void
        | Promise<void>,
        { sequential?: boolean },
    >

    Called only at the end of RolldownBuild.write | bundle.write() once all files have been written.