### Start Development Server with pnpm Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/packages/e2e-tests/env/README.md Use this command to start the Vite development server for local testing and development. ```bash pnpm dev ``` -------------------------------- ### Basic vite.config.js Setup Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md Demonstrates how to pass inline options to the svelte plugin in vite.config.js. ```javascript import { defineConfig } from 'vite'; import svelte from '@sveltejs/vite-plugin-svelte'; export default defineConfig({ plugins: [ svelte({ /* plugin options */ }) ] }); ``` -------------------------------- ### Install Playwright Binaries Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/README.md Install required Playwright browser binaries for development. Note the specific command to use with pnpm. ```bash pnpm playwright install chromium ``` -------------------------------- ### Example Svelte Module File Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt An example of a Svelte module file using rune syntax outside of a component. This file demonstrates state management within a .svelte.ts file. ```ts // src/stores/counter.svelte.ts let count = $state(0); export function increment() { count++; } export function getCount() { return count; } ``` -------------------------------- ### Install @sveltejs/vite-plugin-svelte Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/README.md Install the plugin as a development dependency using npm. ```bash npm install --save-dev @sveltejs/vite-plugin-svelte ``` -------------------------------- ### Dynamic Compile Options Example Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md Use a function to dynamically update compiler options before compilation, such as enabling runes mode based on the filename. This function receives the filename, preprocessed code, and current compiler options, and can return an object with changes. ```javascript import defineConfig from 'vite'; import svelte from '@sveltejs/vite-plugin-svelte'; export default defineConfig({ plugins: [ svelte({ dynamicCompileOptions({ filename, compileOptions }) { // Dynamically set runes mode per Svelte file if (forceRunesMode(filename) && !compileOptions.runes) { return { runes: true }; } } }) ] }); ``` -------------------------------- ### Example Svelte Component with Preprocessed Languages Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Demonstrates a Svelte component utilizing TypeScript in the script tag and SCSS in the style tag, processed by vitePreprocess. ```svelte ``` -------------------------------- ### Import Assets in Svelte Components Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md To use relative paths for assets like images in Svelte components, you must import them first. This example shows how to import an image and use its URL in an `` tag. ```html ``` -------------------------------- ### Custom Vite Plugin to Transform .svelte Files Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Implement a custom Vite plugin to hook into the .svelte file transformation pipeline. This example injects a comment before preprocessing using MagicString. ```js // vite.config.js import { defineConfig } from 'vite'; import { svelte } from '@sveltejs/vite-plugin-svelte'; import MagicString from 'magic-string'; function mySvelteTransform() { const plugin = { name: 'my-svelte-transform', configResolved(config) { // Mirror the exact file filter used by vite-plugin-svelte const svelteIdFilter = config.plugins .find((p) => p.name === 'vite-plugin-svelte:config') ?.api?.filter?.id; if (svelteIdFilter) plugin.transform.filter.id = svelteIdFilter; }, transform: { filter: { id: /\.svelte$/ }, // fallback filter order: 'pre', // run after preprocess, before compile async handler(code, id) { const s = new MagicString(code); // Example: inject a comment at the top of every Svelte file s.prepend('\n'); return { code: s.toString(), map: s.generateMap({ hires: 'boundary', includeContent: false }) }; } } }; // Position options: // Before preprocess: plugin.enforce = 'pre'; plugin.transform.order = 'pre'; // After preprocess, before compile: (no enforce); plugin.transform.order = 'pre'; // After compile: (no enforce); plugin.transform.order = 'post'; return plugin; } export default defineConfig({ plugins: [svelte(), mySvelteTransform()] }); ``` -------------------------------- ### Handle Svelte Compiler Warnings Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md Provides an example of customizing how Svelte compiler warnings are handled, including suppressing specific warnings. ```javascript export default defineConfig({ plugins: [ svelte({ onwarn(warning, defaultHandler) { // don't warn on elements, cos they're cool if (warning.code === 'a11y-distracting-elements') return; // handle all other warnings normally defaultHandler(warning); } }) ] }); ``` -------------------------------- ### Handling Svelte Warnings in Browser Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md Enable sending Svelte warnings to the browser via a websocket message. This is useful for custom browser-based integrations that need to display these warnings. The example shows how to listen for the 'svelte:warnings' event and log the received message. ```javascript import.meta.hot.on('svelte:warnings', (message) => { // handle warnings message, eg log to console console.warn(`Warnings for ${message.filename}`, message.warnings); }); ``` -------------------------------- ### Run Serve Tests Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/README.md Execute serve tests for the plugin using pnpm. ```bash pnpm test:serve ``` -------------------------------- ### Build for Production with pnpm Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/packages/e2e-tests/env/README.md Execute this command to create a production-ready build of your Svelte application. ```bash pnpm build ``` -------------------------------- ### Create SvelteKit Project with Degit Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/packages/e2e-tests/configfile-custom/README.md Use `npx degit` to scaffold a new SvelteKit project from the official template. ```bash npx degit sveltejs/template ``` -------------------------------- ### Basic svelte.config.js Structure Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md Illustrates a basic structure for a svelte.config.js file, including Svelte and plugin options. ```javascript export default { // Svelte options extensions: ['.svelte'], compilerOptions: {}, preprocess: [], onwarn: (warning, handler) => handler(warning), // plugin options vitePlugin: { exclude: [], // experimental options experimental: {} } }; ``` -------------------------------- ### Run Build Tests Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/README.md Execute build tests for the plugin using pnpm. ```bash pnpm test:build ``` -------------------------------- ### Run Unit Tests Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/README.md Execute unit tests for the plugin using pnpm. ```bash pnpm test:unit ``` -------------------------------- ### Configure Vite Preprocessing with vitePreprocess() Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Sets up Svelte preprocessing for TypeScript and CSS languages. Configure script and style preprocessing independently or pass custom Vite configurations. ```javascript import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; export default { // Default: style preprocessing ON, script (TS) preprocessing OFF preprocess: [vitePreprocess()], // Enable script preprocessing for emitting TS constructs (enums, decorators) // preprocess: [vitePreprocess({ script: true })], // Disable CSS preprocessing entirely (e.g. you handle it elsewhere) // preprocess: [vitePreprocess({ style: false })], // Pass a custom Vite InlineConfig for the CSS transform // preprocess: [vitePreprocess({ style: { css: { postcss: { plugins: [] } } } })], }; ``` -------------------------------- ### Configure Svelte Preprocessing Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md Shows how to configure Svelte preprocessing with `svelte-preprocess` and TypeScript support. ```javascript import { defineConfig } from 'vite'; import svelte from '@sveltejs/vite-plugin-svelte'; import sveltePreprocess from 'svelte-preprocess'; export default defineConfig({ plugins: [ svelte({ preprocess: [sveltePreprocess({ typescript: true })] }) ] }); ``` -------------------------------- ### Specify Svelte Config File Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md Shows how to use the `configFile` option to specify a custom Svelte configuration file path. ```javascript import { defineConfig } from 'vite'; import svelte from '@sveltejs/vite-plugin-svelte'; export default defineConfig({ plugins: [ svelte({ configFile: 'my-svelte.config.js' }) ] }); ``` -------------------------------- ### Import Svelte File Content as Raw String Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/advanced-usage.md Use the `?raw` query parameter to import the content of a Svelte file directly as a string, bypassing compilation. ```javascript //get .svelte file content as a string import content from 'File.svelte?raw'; ``` -------------------------------- ### Configure Experimental Svelte Module Compilation Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Set up experimental compilation for Svelte module files (.svelte.js, .svelte.ts) in vite.config.js. Customize infixes, extensions, and include/exclude patterns. ```js // vite.config.js import { defineConfig } from 'vite'; import { svelte } from '@sveltejs/vite-plugin-svelte'; export default defineConfig({ plugins: [ svelte({ experimental: { compileModule: { // File infixes that trigger module compilation (default: ['.svelte.']) infixes: ['.svelte.', '.runes.'], // Module file extensions (default: ['.ts', '.js']) extensions: ['.ts', '.js'], // Fine-grained include/exclude include: /src\/stores\//, exclude: /node_modules/ } } }) ] }); ``` -------------------------------- ### vitePreprocess(opts?) Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt A Svelte preprocessor that delegates script transformation to Vite's TypeScript stripper and style blocks to Vite's CSS pipeline. ```APIDOC ## vitePreprocess(opts?) ### Description Returns a Svelte `PreprocessorGroup` that delegates ` ``` ``` -------------------------------- ### Run Specific E2E Test Suite Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/README.md Focus on a specific end-to-end test suite by providing its directory name to the pnpm test command. ```bash pnpm test ``` -------------------------------- ### Enable script preprocessing with vitePreprocess Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/preprocess.md Enable script preprocessing for advanced TypeScript syntax by setting the `script` option to `true` in vitePreprocess configuration within svelte.config.js. ```javascript // svelte.config.js import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; export default { preprocess: [vitePreprocess({ script: true })] }; ``` -------------------------------- ### Configure Vite with svelte() Plugin Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Integrates Svelte processing into Vite. Configure options like configFile, include/exclude patterns, CSS emission, compiler options, and inspector settings. ```javascript import { defineConfig } from 'vite'; import { svelte } from '@sveltejs/vite-plugin-svelte'; export default defineConfig({ plugins: [ svelte({ // Point to a custom config file (optional) configFile: 'svelte.config.js', // Only process files matching these patterns include: ['src/**/*.svelte'], exclude: ['src/legacy/**'], // Emit Svelte styles as virtual CSS files (default: true) emitCss: true, // Pass options to the Svelte compiler compilerOptions: { // runes mode is auto-detected; force it globally: runes: true }, // Suppress specific compiler warnings onwarn(warning, defaultHandler) { if (warning.code === 'a11y-distracting-elements') return; defaultHandler(warning); }, // Dynamically override compile options per file dynamicCompileOptions({ filename, compileOptions }) { // Force runes mode for specific files at runtime if (filename.includes('/runes/') && !compileOptions.runes) { return { runes: true }; } }, // Disable pre-bundling of Svelte libraries (default: true in dev) prebundleSvelteLibraries: true, // Enable Svelte Inspector in development inspector: { toggleKeyCombo: 'alt-x', showToggleButton: 'always', toggleButtonPos: 'bottom-right' }, // Experimental options experimental: { sendWarningsToBrowser: true } }) ] }); ``` -------------------------------- ### Use vitePreprocess with default settings Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/preprocess.md Configure Svelte preprocessing using vitePreprocess with its default settings in svelte.config.js. This enables default style preprocessing. ```javascript // svelte.config.js import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; export default { preprocess: [vitePreprocess()] }; ``` -------------------------------- ### Load Svelte Config Programmatically Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Use `loadSvelteConfig` to programmatically load the project's Svelte config file within a custom Vite plugin. This utility searches for and imports `svelte.config.*` files. ```javascript import { loadSvelteConfig } from '@sveltejs/vite-plugin-svelte'; function myPlugin() { return { name: 'my-svelte-aware-plugin', async config(viteUserConfig, env) { // Load the project's svelte.config.* file const svelteConfig = await loadSvelteConfig(viteUserConfig, { // configFile: 'svelte.config.js' // optional, explicit path }); if (svelteConfig) { console.log('Svelte extensions:', svelteConfig.extensions); console.log('Compiler options:', svelteConfig.compilerOptions); console.log('Config loaded from:', svelteConfig.configFile); } } }; } ``` -------------------------------- ### Experimental Options Configuration Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md Configure experimental options for vite-plugin-svelte either in your Vite configuration file (`vite.config.js`) or your Svelte configuration file (`svelte.config.js`). These options are subject to change. ```javascript // vite.config.js export default defineConfig({ plugins: [ svelte({ experimental: { // experimental options } }) ] }); ``` ```javascript // svelte.config.js export default { vitePlugin: { experimental: { // experimental options } } }; ``` -------------------------------- ### Dynamic Per-File Compiler Options Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Use `dynamicCompileOptions` in `vite.config.js` to provide per-file runtime compiler option overrides. This is useful for gradual migrations or enabling experimental features on a per-directory basis. ```javascript // vite.config.js import { defineConfig } from 'vite'; import { svelte } from '@sveltejs/vite-plugin-svelte'; export default defineConfig({ plugins: [ svelte({ dynamicCompileOptions({ filename, compileOptions }) { // Migrate to runes one directory at a time if (filename.includes('/src/new/') && !compileOptions.runes) { return { runes: true }; } // Force legacy mode for old components if (filename.includes('/src/legacy/') && compileOptions.runes) { return { runes: false }; } // No override needed for other files } }) ] }); ``` -------------------------------- ### SvelteKit HTML Structure Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/packages/e2e-tests/kit-node/src/app.html Standard HTML structure for a SvelteKit application, with placeholders for dynamically injected head and body content. ```html %sveltekit.head% %sveltekit.body% ``` -------------------------------- ### svelte(inlineOptions?) Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt The main Vite plugin factory that returns an array of Vite Plugin objects to handle Svelte processing. It merges inline options with any discovered svelte.config.* file. ```APIDOC ## svelte(inlineOptions?) ### Description Returns an array of Vite `Plugin` objects that collectively handle every aspect of Svelte processing: configuration resolution, dependency pre-bundling, CSS emission, preprocessing, compilation of `.svelte` components and `.svelte.js` modules, HMR, and the Inspector. The `inlineOptions` object merges with any discovered `svelte.config.*` file. ### Method `svelte(inlineOptions?)` ### Parameters #### Inline Options - **configFile** (string) - Optional - Point to a custom config file (e.g., 'svelte.config.js'). - **include** (string[]) - Optional - Only process files matching these patterns. - **exclude** (string[]) - Optional - Exclude files matching these patterns. - **emitCss** (boolean) - Optional - Emit Svelte styles as virtual CSS files (default: true). - **compilerOptions** (object) - Optional - Pass options to the Svelte compiler. - **runes** (boolean) - Optional - Force runes mode globally. - **onwarn** (function) - Optional - Suppress specific compiler warnings. - **dynamicCompileOptions** (function) - Optional - Dynamically override compile options per file. - **filename** (string) - The name of the file being compiled. - **compileOptions** (object) - The current compile options. - Returns an object with dynamic compile options. - **prebundleSvelteLibraries** (boolean) - Optional - Disable pre-bundling of Svelte libraries (default: true in dev). - **inspector** (object) - Optional - Enable Svelte Inspector in development. - **toggleKeyCombo** (string) - Key combination to toggle the inspector. - **showToggleButton** (string) - Controls the visibility of the toggle button ('always', 'never', 'active'). - **toggleButtonPos** (string) - Position of the toggle button ('top-left', 'top-right', 'bottom-left', 'bottom-right'). - **experimental** (object) - Optional - Experimental options. - **sendWarningsToBrowser** (boolean) - Optional - Send warnings to the browser. ### Request Example ```js // vite.config.js import { defineConfig } from 'vite'; import { svelte } from '@sveltejs/vite-plugin-svelte'; export default defineConfig({ plugins: [ svelte({ configFile: 'svelte.config.js', include: ['src/**/*.svelte'], exclude: ['src/legacy/**'], emitCss: true, compilerOptions: { runes: true }, onwarn(warning, defaultHandler) { if (warning.code === 'a11y-distracting-elements') return; defaultHandler(warning); }, dynamicCompileOptions({ filename, compileOptions }) { if (filename.includes('/runes/') && !compileOptions.runes) { return { runes: true }; } }, prebundleSvelteLibraries: true, inspector: { toggleKeyCombo: 'alt-x', showToggleButton: 'always', toggleButtonPos: 'bottom-right' }, experimental: { sendWarningsToBrowser: true } }) ] }); ``` ``` -------------------------------- ### Configure Vite with @sveltejs/vite-plugin-svelte Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/README.md Integrate the Svelte plugin into your Vite configuration file (vite.config.js). ```javascript // vite.config.js import { defineConfig } from 'vite'; import { svelte } from '@sveltejs/vite-plugin-svelte'; export default defineConfig({ plugins: [ svelte({ /* plugin options */ }) ] }); ``` -------------------------------- ### Configure Svelte Library Pre-bundling in Vite Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Control whether Svelte component libraries are added to Vite's `optimizeDeps`. This is enabled by default in dev for faster initial page loads. Use `disableDependencyReinclusion` to opt out specific libraries. ```javascript // vite.config.js — tuning pre-bundling behaviour import { defineConfig } from 'vite'; import { svelte } from '@sveltejs/vite-plugin-svelte'; export default defineConfig({ plugins: [ svelte({ // Disable pre-bundling for ALL Svelte libraries prebundleSvelteLibraries: false, // OR disable re-inclusion of sub-deps only for hybrid packages disableDependencyReinclusion: ['routify'] }) ], optimizeDeps: { // Manually exclude a specific library from pre-bundling exclude: ['some-huge-icon-library'], // Manually re-include a sub-dep of an excluded parent include: ['some-huge-icon-library > lodash-es'] } }); ``` -------------------------------- ### Enable Vite Plugin Svelte Debug Logging Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md To troubleshoot configuration issues, enable debug logging for vite-plugin-svelte by setting the DEBUG environment variable. This helps in identifying problems within the configuration process. ```bash DEBUG=vite-plugin-svelte:config vite dev ``` ```bash DEBUG=vite-plugin-svelte:* vite dev ``` ```bash DEBUG=* vite dev ``` -------------------------------- ### Create Custom Vite Plugin for Svelte Transforms Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/advanced-usage.md Implement a custom Vite plugin to transform Svelte files. Use `enforce` and `transform.order` to control its execution relative to `vite-plugin-svelte`'s internal plugins. ```javascript function mySvelteTransform() { const plugin = { name: 'vite-plugin-my-svelte-transformer', configResolved(c) { // optional, use the exact same id filter as vite-plugin-svelte itself const svelteIdFilter = c.plugins.find((p) => p.name === 'vite-plugin-svelte:config').api .filter.id; plugin.transform.filter.id = svelteIdFilter; }, transform: { // if you don't use vite-plugin-svelte's filter make sure to include your own here filter: { id: /your id filter here/ }, async handler(code, id) { const s = new MagicString(code); // do your transforms with s return { code: s.toString(), map: s.generateMap({ hires: 'boundary', includeContent: false }) }; } } }; // To add your transform in the correct place use `enforce` and `transform.order` // before preprocess plugin.enforce = 'pre'; plugin.transform.order = 'pre'; // after preprocess but before compile plugin.transform.order = 'pre'; // leave plugin.enforce undefined // after compile plugin.transform.order = 'post'; // leave plugin.enforce undefined return plugin; } ``` -------------------------------- ### Configure Vite with Svelte Plugin Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/packages/vite-plugin-svelte/README.md Integrate the Svelte plugin into your Vite configuration file (vite.config.js) to enable Svelte support. This is the standard way to set up the plugin for a Vite project. ```js import { defineConfig } from 'vite'; import { svelte } from '@sveltejs/vite-plugin-svelte'; export default defineConfig({ plugins: [ svelte({ /* plugin options */ }) ] }); ``` -------------------------------- ### Use Vite Plugin Svelte with CommonJS Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md When using CommonJS with Vite, ensure you are using Node.js v20.19+ for 'require esm' support. This configuration demonstrates how to set up the Vite configuration file using CommonJS syntax. ```javascript // vite.config.cjs const { defineConfig } = require('vite'); const { svelte, vitePreprocess } = require('@sveltejs/vite-plugin-svelte'); module.exports = defineConfig({ plugins: [svelte({ preprocess: vitePreprocess() })] }); ``` -------------------------------- ### Configure Inspector with Environment Variables Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/inspector.md Configure Svelte Inspector options using environment variables for personal preferences. These settings take precedence over the Svelte config. ```shell # just keycombo, unquoted string SVELTE_INSPECTOR_TOGGLE=alt-x ``` ```shell # options object as json SVELTE_INSPECTOR_OPTIONS='{"holdMode": false, "toggleButtonPos": "bottom-left"}' ``` ```shell # disable completely SVELTE_INSPECTOR_OPTIONS=false ``` ```shell # force default options SVELTE_INSPECTOR_OPTIONS=true ``` -------------------------------- ### External Svelte Configuration File Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Define Svelte configurations in `svelte.config.js` (or `.mjs`, `.ts`, `.mts`) for automatic loading by `vite-plugin-svelte`. Plugin-specific options are placed under the `vitePlugin` key. ```javascript // svelte.config.js import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; import sveltePreprocess from 'svelte-preprocess'; // optional third-party export default { // Svelte compiler options (shared by all integrations) extensions: ['.svelte', '.svx'], preprocess: [ vitePreprocess(), // Use svelte-preprocess only for features vitePreprocess doesn't cover sveltePreprocess({ globalStyle: true }) ], compilerOptions: { runes: false // opt-out of runes globally }, onwarn(warning, handler) { // Silence accessibility warnings in production builds if (process.env.NODE_ENV === 'production' && warning.code.startsWith('a11y')) return; handler(warning); }, // vite-plugin-svelte specific options vitePlugin: { inspector: true, prebundleSvelteLibraries: true, disableDependencyReinclusion: false, experimental: { sendWarningsToBrowser: false } } }; ``` -------------------------------- ### Configure Svelte Compiler Options Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Pass Svelte compiler options, such as `runes` and `cssHash`, directly to `vite-plugin-svelte` via the `compilerOptions` property in `vite.config.js`. The plugin manages `dev`/`hmr`/`css` automatically. ```javascript // vite.config.js import { defineConfig } from 'vite'; import { svelte } from '@sveltejs/vite-plugin-svelte'; export default defineConfig({ plugins: [ svelte({ compilerOptions: { // Enable runes mode globally (Svelte 5) runes: true, // Use custom CSS hash that depends only on filename (required for good HMR) cssHash: ({ hash, filename }) => `my-app-${hash(filename)}`, // Svelte 5 warning filter (alternative to onwarn) warningFilter: (warning) => !['a11y_hidden', 'state_snapshot_uncloneable'].includes(warning.code) } }) ] }); ``` -------------------------------- ### Forward Svelte Compiler Warnings to the Browser Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Enable `experimental.sendWarningsToBrowser` to forward Svelte compiler warnings via WebSocket messages (`svelte:warnings`) for custom browser-side tooling. ```javascript // vite.config.js import { defineConfig } from 'vite'; import { svelte } from '@sveltejs/vite-plugin-svelte'; export default defineConfig({ plugins: [ svelte({ experimental: { sendWarningsToBrowser: true } }) ] }); ``` ```javascript // Browser-side handler (e.g. in main.js or a dev overlay) if (import.meta.hot) { import.meta.hot.on('svelte:warnings', (message) => { // message shape: // { // id: string, // filename: string, // normalizedFilename: string, // timestamp: number, // warnings: Warning[], // filtered by onwarn // allWarnings: Warning[], // including filtered // rawWarnings: Warning[] // raw compiler output // } if (message.warnings.length) { console.group(`[svelte warnings] ${message.filename}`); message.warnings.forEach((w) => console.warn(w.code, w.message)); console.groupEnd(); } }); } ``` -------------------------------- ### Hydration Mark Initial Node Function Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/packages/e2e-tests/kit-node/src/app.html JavaScript function to mark initial DOM nodes for hydration. This is typically used internally by SvelteKit during the client-side rendering process. ```javascript function markInitialNode(id) { const el = document.getElementById(id); if (el) { el." __initialNode = true; } } ['load', 'mount'].forEach(markInitialNode); ``` -------------------------------- ### Enable Inspector with Custom Options Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/inspector.md Configure the Svelte Inspector with custom options such as key combinations and toggle button visibility in `svelte.config.js`. ```javascript // svelte.config.js export default { vitePlugin: { inspector: { toggleKeyCombo: 'alt-x', showToggleButton: 'always', toggleButtonPos: 'bottom-right' } } }; ``` -------------------------------- ### Debug Vite Plugin Svelte with DEBUG environment variable Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Use the `DEBUG` environment variable to enable detailed logging for Vite plugin Svelte, aiding in debugging configuration resolution, compilation statistics, and general plugin behavior. ```shell # Show config resolution details DEBUG=vite-plugin-svelte:config vite dev # Show compile-time statistics (useful for tuning index vs deep imports) DEBUG=vite-plugin-svelte:stats vite dev # Show all vite-plugin-svelte debug output DEBUG=vite-plugin-svelte:* vite dev ``` -------------------------------- ### Recommended Svelte SFC File Order Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md The order of nodes in a Svelte Single File Component (SFC) impacts HMR performance. Place the ` ``` ```html
``` -------------------------------- ### Exclude Libraries from Vite Prebundling Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md Configure `optimizeDeps.exclude` in `vite.config.js` to prevent specific libraries from being pre-bundled. This is useful for libraries that may not work well with Vite's prebundling process. ```javascript // vite.config.js export default defineConfig({ optimizeDeps: { exclude: ['some-library'] // do not pre-bundle some-library } }); ``` -------------------------------- ### Generate Types Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/README.md Generate public types from JSDoc comments. This is a required step when changing types and is validated in CI. ```bash pnpm generate:types ``` -------------------------------- ### Configure Svelte Inspector via Environment Variables Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Override Svelte Inspector configuration using environment variables. Options can be set individually or as a JSON string for comprehensive control. ```shell # Enable with default options SVELTE_INSPECTOR_OPTIONS=true # Custom key combo only SVELTE_INSPECTOR_TOGGLE=control-shift # Full options as JSON SVELTE_INSPECTOR_OPTIONS='{"toggleKeyCombo":"alt-i","showToggleButton":"always","holdMode":false}' # Disable completely SVELTE_INSPECTOR_OPTIONS=false ``` -------------------------------- ### Disable Automatic Config File Handling Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/config.md Demonstrates how to disable the automatic reading of Svelte config files using `configFile: false`. ```javascript import { defineConfig } from 'vite'; import svelte from '@sveltejs/vite-plugin-svelte'; export default defineConfig({ plugins: [ svelte({ configFile: false // your Svelte config here }) ] }); ``` -------------------------------- ### Svelte 5 Component with SSR Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/packages/e2e-tests/import-queries/__tests__/__snapshots__/svelte-5/ssr-raw.txt This Svelte component includes state management and event handling. It's designed for raw SSR, meaning the initial HTML is generated on the server. ```svelte ``` -------------------------------- ### Configure Svelte Inspector in svelte.config.js Source: https://context7.com/sveltejs/vite-plugin-svelte/llms.txt Configure Svelte Inspector options like key combos, navigation keys, and toggle button behavior within svelte.config.js. These options can be overridden by environment variables. ```js // svelte.config.js — full inspector configuration export default { vitePlugin: { inspector: { // Key combo to toggle inspector (default: 'alt-x') toggleKeyCombo: 'control-shift', // Keyboard navigation keys navKeys: { parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' }, // Key to open editor for selected element (default: 'Enter') openKey: 'Enter', // Keys to close the inspector escapeKeys: ['Backspace', 'Escape'], // Hold mode: inspector active only while key is held (default: true) holdMode: true, // When to show the floating toggle button: 'always' | 'active' | 'never' showToggleButton: 'always', // Toggle button position toggleButtonPos: 'top-right', // Inject inspector CSS (adds `svelte-inspector-enabled` class to ) customStyles: true } } }; ``` -------------------------------- ### Enable Inspector in Svelte Config Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/inspector.md Enable the Svelte Inspector by setting the `inspector` option to `true` in your `svelte.config.js` file. ```javascript // svelte.config.js export default { vitePlugin: { inspector: true } }; ``` -------------------------------- ### Disable Prebundling for Svelte Libraries Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md Set `prebundleSvelteLibraries` to `false` in `svelte.config.js` to disable prebundling for all Svelte libraries. This can be a workaround if prebundling causes issues with Svelte-specific dependencies. ```javascript // svelte.config.js export default { vitePlugin: { prebundleSvelteLibraries: false } }; ``` -------------------------------- ### Customize CSS Hash Prefix in Svelte Config Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md Customize the `cssHash` function in `svelte.config.js` to modify the prefix used for CSS class names. This can help ensure styles are scoped correctly and prevent unwanted JS updates during CSS changes. ```javascript // svelte.config.js export default { compilerOptions: { cssHash: ({ hash, filename, css }) => `my-custom-prefix-${hash(filename ?? css)}` } }; ``` -------------------------------- ### Add Svelte Export Condition to package.json Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md Update your `package.json` to include the `svelte` export condition within the `exports` map. This is the modern standard for Svelte packages and ensures compatibility with tools like vite-plugin-svelte. ```json // package.json "files": ["dist"], "svelte": "dist/index.js", + "exports": { + ".": { + "svelte": "./dist/index.js" + } } ``` -------------------------------- ### TypeScript in Svelte Script Tags Source: https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md When using TypeScript within Svelte script tags, ensure you use the `lang="ts"` attribute. Vite will not recognize `lang="typescript"` or `type="text/typescript"`. ```html ``` ```html ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.