Install @preact/preset-vite
mainInstall the @preact/preset-vite package as a development dependency using npm or yarn to enable Preact features in your Vite project.
npm install --save-dev @preact/preset-vite
# or
yarn add -D @preact/preset-viterepository·main·Indexed 43 days ago
https://github.com/preactjs/preset-viteAn all-in-one Vite plugin (@preact/preset-vite v2.10.6) to streamline Preact development. It provides HMR via Prefresh, Preact Devtools integration, automatic React compatibility aliasing to preact/compat, and support for static site prerendering.
Install the @preact/preset-vite package as a development dependency using npm or yarn to enable Preact features in your Vite project.
npm install --save-dev @preact/preset-vite
# or
yarn add -D @preact/preset-viteTo use prerendering, follow these steps:
enabled: true).renderTarget (e.g., '#app') that matches the selector used in your client-side render() call.prerender() function in a script. This function must be exported and should return an object containing an html property (the rendered string). You can use libraries like preact-render-to-string or preact-iso to generate this.<script prerender src="..."> tag to your HTML entrypoint or specify the absolute path using the prerenderScript plugin option.The prerender() function can be asynchronous, allowing for data fetching or file system access during the build process.
import { prerender as ssr } from 'preact-iso';
function App() {
return <h1>Hello World!</h1>
}
export async function prerender(data) {
const { html, links: discoveredLinks } = ssr(<App />);
return {
html,
// Optionally add additional links that should be
// prerendered (that haven't already been)
links: new Set([...discoveredLinks, '/foo', '/bar']),
// Optional data to serialize into a script tag for use on the client:
// <script type="application/json" id="preact-prerender-data">{"url":"/"}</script>
data: { url: data.url },
// Optionally configure and add elements to the `<head>` of
// the prerendered HTML document
head: {
// Sets the "lang" attribute: `<html lang="en">`
lang: 'en',
// Sets the title for the current page: `<title>My cool page</title>`
title: 'My cool page',
// Sets any additional elements you want injected into the `<head>`:
elements: new Set([
{ type: 'link', props: { rel: 'stylesheet', href: 'foo.css' } },
{ type: 'meta', props: { property: 'og:title', content: 'Social media title' } }
])
}
};
}To use the preset, add the preact() plugin to your vite.config.ts or vite.config.js file using defineConfig.
import { defineConfig } from "vite";
import preact from "@preact/preset-vite";
export default defineConfig({
plugins: [preact()]
});The prerender option allows you to enable and configure static site prerendering for your Preact application.
preact({
prerender: {
enabled: true,
renderTarget: '#app',
prerenderScript: '/path/to/script.js',
additionalPrerenderRoutes: ['/404'],
previewMiddlewareEnabled: true,
previewMiddlewareFallback: '/index.html'
}
})Use the babel option to add plugins, presets, and other configuration to the Babel transformation applied to each JSX/TSX file. Plugins provided here run before built-in transforms like Fast Refresh.
preact({
babel: {
presets: [...],
// Your plugins run before any built-in transform (eg: Fast Refresh)
plugins: [...],
// Use .babelrc files
babelrc: true,
// Use babel.config.js files
configFile: true,
}
})You can customize the behavior of the Preact preset by passing an options object to the preact() plugin function.
Key features included by default:
prefresh.react and react-dom to preact/compat.export default defineConfig({
plugins: [
preact({ devtoolsInProd: true })
]
});You can pass an options object to preact() to customize its behavior.
| Option | Type | Default | Description |
|---|---|---|---|
devtoolsInProd | boolean | false | Inject devtools bridge in production bundle instead of only in development mode. |
devToolsEnabled | boolean | true | Whether to use Preact devtools. |
prefreshEnabled | boolean | true | Whether to use prefresh HMR. |
reactAliasesEnabled | boolean | true | Whether to alias react and react-dom to preact/compat. |
include | FilterPattern | [/[\.[cm]?[tj]sx?$/] | RegExp or glob to match files to be transformed. |
exclude | FilterPattern | [/node_modules/] | RegExp or glob to match files to NOT be transformed. |
babel | BabelOptions | undefined | Babel configuration applied in both dev and prod. |
jsxImportSource | string | "preact" | Import Source for jsx. |
prerender | object | { enabled: false } | Configuration for the prerender plugin. |
| Option | Type | Description |
|---|---|---|
enabled | boolean | Whether to prerender your app on build. |
prerenderScript | string | Absolute path to script containing an exported prerender() function. |
renderTarget | string | Query selector for specifying where to insert prerender result in your HTML template. |
additionalPrerenderRoutes | string[] | Additional routes that should be prerendered. |
previewMiddlewareEnabled | boolean | If true, corrects Vite's preview server to use prerendered HTML. |
previewMiddlewareFallback | string | Path to use as a fallback/404 route (e.g., /404). |
import { preact } from '@preact/preset-vite';
preact({
devtoolsInProd: true,
reactAliasesEnabled: true,
prerender: {
enabled: true,
prerenderScript: './prerender.js',
renderTarget: '#app',
additionalPrerenderRoutes: ['/about', '/contact']
}
});The following options are available within the prerender object:
| Option | Type | Default | Description |
|---|---|---|---|
enabled | boolean | false | Enables prerendering |
renderTarget | string | "body" | Query selector for where to insert prerender result in your HTML template |
prerenderScript | string | undefined | Absolute path to script containing exported prerender() function. If not provided, will try to find the prerender script in the scripts listed in your HTML entrypoint |
additionalPrerenderRoutes | string[] | undefined | Prerendering will crawl your site automatically, but you'd like to prerender some pages that may not be found (such as a /404 page), use this option to specify them |
previewMiddlewareEnabled | boolean | false | Vite's preview server as of v5 will not use our prerendered HTML documents automatically. This option enables a middleware that will correct this, allowing you to test the result of prerendering locally |
previewMiddlewareFallback | string | /index.html | Fallback path to be used when an HTML document cannot be found via the preview middleware, e.g., /404 or /not-found will be used when the user requests /some-path-that-does-not-exist |
The following options are available for the preact() plugin:
| Option | Type | Default | Description |
|---|---|---|---|
devtoolsInProd | boolean | false | Inject devtools bridge in production bundle instead of only in development mode |
devToolsEnabled | boolean | true | Inject devtools bridge |
prefreshEnabled | boolean | true | Inject Prefresh for HMR |
reactAliasesEnabled | boolean | true | Aliases react, react-dom to preact/compat |
babel | object | See Babel configuration | |
prerender | object | See Prerendering configuration |
The preact plugin (exported as the default or via the preactPlugin named export) integrates Preact into a Vite project. It handles JSX transformation, provides Preact DevTools support, enables HMR via prefresh, and can automatically alias react and react-dom to preact/compat to support React ecosystem libraries.
import { preact } from '@preact/preset-vite';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [preact()]
});The transformHookNamesPlugin is a Vite plugin used to assist with Preact DevTools by injecting addHookName calls around specific hook usages (like useState, useReducer, useRef, or useMemo). This helps DevTools identify which variable name is associated with a hook.
To use this plugin, you must provide a shouldTransform filter function to determine which files should be processed.
transformHookNamesPlugin({
shouldTransform: (id) => id.endsWith('.ts'), // Example filter
devtoolsInProd: false,
devToolsEnabled: true
});The preactDevtoolsPlugin is a Vite plugin used to inject the Preact Devtools bridge or Preact debug utilities into your application. It can be configured via the PreactDevtoolsPluginOptions object.
| Option | Type | Default | Description |
|---|---|---|---|
devtoolsInProd | boolean | false | If true, the devtools bridge will be injected even in production builds. |
devToolsEnabled | boolean | Calculated | Explicitly enables or disables the plugin. If not provided, it defaults to true in development and false in production (unless devtoolsInProd is true). |
shouldTransform | RollupFilter | Required | A function used to determine which files should be eligible for the injection process. |
import { preactDevtoolsPlugin } from '@preact/preset-vite';
// Example configuration
export default {
plugins: [
preactDevtoolsPlugin({
devtoolsInProd: false,
devToolsEnabled: true,
shouldTransform: (id) => id.includes('src/main.tsx'),
}),
],
};