diff --git a/.prettierrc.js b/.prettierrc.js index 8d1916460..61eb680cf 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -33,7 +33,12 @@ export default { } }, { - files: ['**/package.json', '**/README.md', 'docs/**/*.md', '.changeset/pre.json'], + files: [ + '**/package.json', + '**/README.md', + 'documentation/docs/**/*.md', + '.changeset/pre.json' + ], options: { useTabs: false, tabWidth: 2 diff --git a/docs/__symlinks_only__.txt b/docs/__symlinks_only__.txt new file mode 100644 index 000000000..510aec711 --- /dev/null +++ b/docs/__symlinks_only__.txt @@ -0,0 +1,3 @@ +These symlinks ensure that preexisting links to the old documentation format keep working. + +Please use the new structure in documentation/docs to edit it. diff --git a/docs/advanced-usage.md b/docs/advanced-usage.md deleted file mode 100644 index 9d3cd31c6..000000000 --- a/docs/advanced-usage.md +++ /dev/null @@ -1,65 +0,0 @@ -# Advanced usage - -> **HERE BE DRAGONS** -> -> The features described here are not meant to be used in regular libraries or end-user applications. -> They can be useful for frameworks, documentation sites or in special situations, but you are responsible for applying them correctly. -> -> **Proceed with caution!** - -## transform svelte files with vite plugins - -vite-plugin-svelte uses 2 Vite plugins `vite-plugin-svelte:preprocess` and `vite-plugin-svelte:compile` to preprocess and compile input. -The preprocess plugin uses `enforce: pre` but the compile plugin does not, giving you fine-grained control to add your own transforms - -```js -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; -} -``` - -## custom queries - -Vite supports using query parameters to request different outcomes for the same file. - -The following schemes are supported by vite-plugin-svelte: - -### raw - -```js -//get .svelte file content as a string -import content from 'File.svelte?raw'; -``` diff --git a/docs/advanced-usage.md b/docs/advanced-usage.md new file mode 120000 index 000000000..b5f1b5849 --- /dev/null +++ b/docs/advanced-usage.md @@ -0,0 +1 @@ +../documentation/docs/10-plugin/20-advanced-usage.md \ No newline at end of file diff --git a/docs/config.md b/docs/config.md deleted file mode 100644 index 3d5921236..000000000 --- a/docs/config.md +++ /dev/null @@ -1,338 +0,0 @@ -# Configuration - -`vite-plugin-svelte` accepts inline options that can be used to change its behaviour. An object can be passed to the first argument of the `svelte` plugin: - -```js -// vite.config.js -export default defineConfig({ - plugins: [ - svelte({ - /* plugin options */ - }) - ] -}); -``` - -Explore the various options below! - -## Config file - -### Config file resolving - -Besides inline options in Vite config, `vite-plugin-svelte` will also automatically resolve options from a Svelte config file if one exists. The default search paths are: - -- `svelte.config.js` -- `svelte.config.mjs` -- `svelte.config.ts` -- `svelte.config.mts` - -To set a specific config file, use the `configFile` inline option. The path can be absolute or relative to the [Vite root](https://vitejs.dev/config/#root). For example: - -```js -// vite.config.js -export default defineConfig({ - plugins: [ - svelte({ - configFile: 'my-svelte.config.js' - }) - ] -}); -``` - -A basic Svelte config looks like this: - -```js -// svelte.config.js -export default { - // Svelte options - extensions: ['.svelte'], - compilerOptions: {}, - preprocess: [], - onwarn: (warning, handler) => handler(warning), - // plugin options - vitePlugin: { - exclude: [], - // experimental options - experimental: {} - } -}; -``` - -### Config file extension - -The Svelte config should always be written in ESM syntax. Depending on Node's mode, make sure you're using the correct extension. - -- If `type: "module"` is defined in `package.json`, prefer `.js` or `.ts` -- If `type: "module"` is not defined, use `.mjs` or `.mts` - -> Try to stick with the `.js` extension whenever possible. - -### Disable automatic handling of Svelte config - -Use `configFile: false` to prevent `vite-plugin-svelte` from reading the config file or restarting the Vite dev server when it changes. - -```js -// vite.config.js -export default defineConfig({ - plugins: [ - svelte({ - configFile: false - // your Svelte config here - }) - ] -}); -``` - -> Warning: -> This option primarily exists for frameworks like SvelteKit that do their own parsing of Svelte config and control the Vite dev server. -> You are responsible to provide the complete inline config when used. - -## Svelte options - -These options are specific to the Svelte compiler and are generally shared across many bundler integrations. - -### compilerOptions - -- **Type:** `CompileOptions` - See [svelte.compile](https://svelte.dev/docs/svelte/svelte-compiler#CompileOptions) - - The options to be passed to the Svelte compiler. A few options are set by default, including `dev` and `css`. However, some options are non-configurable, like `filename`, `format`, `generate`, and `cssHash` ([in dev](./faq.md#why-cant-csshash-be-set-in-development-mode)). - -### preprocess - -- **Type:** `PreprocessorGroup | PreprocessorGroup[]` - See [svelte.preprocess](https://svelte.dev/docs#compile-time-svelte-preprocess) - - An array of preprocessors to transform the Svelte source code before compilation. - - **Example:** - - ```js - // vite.config.js - import sveltePreprocess from 'svelte-preprocess'; - - export default defineConfig({ - plugins: [ - svelte({ - preprocess: [sveltePreprocess({ typescript: true })] - }) - ] - }); - ``` - -### extensions - -- **Type:** `string[]` -- **Default:** `['.svelte']` - - A list of file extensions to be compiled by Svelte. Useful for custom extensions like `.svg` and `.svx`. - -### onwarn - -- **Type:** `(warning: Warning, defaultHandler: (warning: Warning) => void) => void` - See [Warning](https://github.com/sveltejs/svelte/blob/ce550adef65a7e04c381b11c24f07a2ae1c25783/src/compiler/interfaces.ts#L121-L130) - - Handles warning emitted from the Svelte compiler. Useful to suppress warning messages. - - **Example:** - - ```js - 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); - } - }) - ] - }); - ``` - - In addition, Svelte 5's compiler interface also provides a way to filter warnings using the `warningFilter` setting as described in [Svelte 5's docs](https://svelte.dev/docs/svelte/svelte-compiler#ModuleCompileOptions). - -## Plugin options - -These options are specific to the Vite plugin itself. - -### include - -- **Type:** `string | string[]` -- **Default:** unset - -A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files the plugin should operate on **in addition** to the files ending with one of the configured extensions. - -### exclude - -- **Type:** `string | string[]` -- **Default:** unset - -A [picomatch pattern](https://github.com/micromatch/picomatch), or array of patterns, which specifies the files to be ignored by the plugin. By default, no files are ignored. - -### emitCss - -- **Type:** `boolean` -- **Default:** `true` - - Emit Svelte styles as virtual CSS files for Vite and other plugins to process. - -### hot - -- **Deprecated**: use compileOptions.hmr instead -- **Type:** `boolean` -- **Default:** `true` for development, always `false` for production - -### ignorePluginPreprocessors - -- **Type:** `boolean | string[]` -- **Default:** `false` - - Some Vite plugins can contribute additional preprocessors by defining [api.sveltePreprocess](./faq.md#how-do-i-add-a-svelte-preprocessor-from-a-vite-plugin). If you don't want to use them, set this to true to ignore them all or use an array of strings with plugin names to specify which. - -### disableDependencyReinclusion - -- **Type:** `boolean | string[]` -- **Default:** `false` - - `vite-plugin-svelte` automatically manages [pre-bundling for Svelte components](./faq.md#what-is-going-on-with-vite-and-pre-bundling-dependencies). To opt-out of this automatic behavior you can use: - - `disableDependencyReinclusion: true` to disable all re-inclusions - - `disableDependencyReinclusion: ['foo']` to disable re-inclusions only for dependencies of `foo`. - - If you want to manually re-include the dependency `bar` of `foo`, you can add `{optimizeDeps:{include:['foo > bar']}}` to your Vite config - - > This is currently required for hybrid packages like Routify, that export both Node and browser code. - -### prebundleSvelteLibraries - -- **Type:** `boolean` -- **Default:** `true` for dev, `false` for build - - Enable [Vite's dependency prebundling](https://vitejs.dev/guide/dep-pre-bundling.html) for Svelte libraries. - - This option improves page loading for the dev server in most applications when using Svelte component libraries. - - See the [FAQ](./faq.md#what-is-going-on-with-vite-and-pre-bundling-dependencies) for details and how to fine-tune it for huge libraries. - -### inspector - -- **Type:** `InspectorOptions | boolean` -- **Default:** `unset` for dev, always `false` for build - - Set to `true` or options object to enable Svelte inspector during development. See the [inspector docs](./inspector.md) for the full configuration options. - - Inspector mode shows you the file location where the element under cursor is defined and you can click to quickly open your code editor at this location. - -### dynamicCompileOptions - -- **Type:** - - ```ts - type DynamicCompileOptions = (data: { - filename: string; // The file to be compiled - code: string; // The preprocessed Svelte code - compileOptions: Partial; // The current compiler options - }) => Promise | void> | Partial | void; - ``` - - A function to update the `compilerOptions` before compilation. To change part of the compiler options, return an object with the changes you need. - - **Example:** - - ```js - // vite.config.js - export default defineConfig({ - plugins: [ - svelte({ - dynamicCompileOptions({ filename, compileOptions }) { - // Dynamically set runes mode per Svelte file - if (forceRunesMode(filename) && !compileOptions.runes) { - return { runes: true }; - } - } - }) - ] - }); - ``` - -## Experimental options - -These options are considered experimental and breaking changes to them can occur in any release! Specify them under the `experimental` option. - -Either in Vite config: - -```js -// vite.config.js -export default defineConfig({ - plugins: [ - svelte({ - experimental: { - // experimental options - } - }) - ] -}); -``` - -or in Svelte config: - -```js -// svelte.config.js -export default { - vitePlugin: { - experimental: { - // experimental options - } - } -}; -``` - -### sendWarningsToBrowser - -- **Type:** `boolean` -- **Default:** `false` - - Sends a websocket message `svelte:warnings` with the warnings that are passed to `onwarn`. This is only useful if you build a custom browser based integration where you want to display these. - - **Example** - - ```js - import.meta.hot.on('svelte:warnings', (message) => { - // handle warnings message, eg log to console - console.warn(`Warnings for ${message.filename}`, message.warnings); - }); - ``` - - **Message format** - - ```ts - type SvelteWarningsMessage = { - id: string; - filename: string; - normalizedFilename: string; - timestamp: number; - warnings: Warning[]; // allWarnings filtered by warnings where onwarn did not call the default handler - allWarnings: Warning[]; // includes warnings filtered by onwarn and our extra vite-plugin-svelte warnings - rawWarnings: Warning[]; // raw compiler output - }; - ``` - -### disableSvelteResolveWarnings - -- **Type** `boolean` -- **Default:** `false` - - disable Svelte resolve warnings. Note: this is highly discouraged and you should instead fix these packages which will break in the future. - -### disableApiSveltePreprocessWarnings - -- **Type** `boolean` -- **Default:** `false` - - disable api.sveltePreprocess deprecation warnings - -### compileModule - -- **Type** `CompileModuleOptions` -- **Default:** `undefined` - - set custom compile options for compilation of Svelte modules (`.svelte.js` files). diff --git a/docs/config.md b/docs/config.md new file mode 120000 index 000000000..61d7666d5 --- /dev/null +++ b/docs/config.md @@ -0,0 +1 @@ +../documentation/docs/10-plugin/10-config.md \ No newline at end of file diff --git a/docs/faq.md b/docs/faq.md deleted file mode 100644 index dc09c840f..000000000 --- a/docs/faq.md +++ /dev/null @@ -1,234 +0,0 @@ -# Frequently Asked Questions - -### Something is wrong with my config, how can I find where the problem comes from? - -`vite` and `vite-plugin-svelte` can be made more verbose by using the debug mode (powered by and following the conventions of the [`debug`](https://github.com/debug-js/debug) library): - -- `DEBUG=vite-plugin-svelte:config vite dev`: log `vite-plugin-svelte` debug info related to the config -- `DEBUG=vite-plugin-svelte:* vite dev`: log all `vite-plugin-svelte` debug info -- `DEBUG=* vite dev`: log all debug info - -### Why is component state reset on HMR update? - -Preservation of local component state after JS updates is disabled to avoid unpredictable and error-prone behavior. -Since svelte-5, hmr is integrated in compileOptions, but the sentiment in the previously used [svelte-hmr docs](https://github.com/sveltejs/svelte-hmr/blob/master/packages/svelte-hmr#preservation-of-local-state) still applies. - -Please note that if you only edit the ` -``` - -Bad: - -```html - - - -
-``` - -### Why isn't Vite detecting my imports correctly in `.svelte` files with TypeScript? - -You have to use the `lang="ts"` attribute for Vite to parse it. Never `lang="typescript"` or `type="text/typescript"`. - -Good: - -```html - -``` - -Bad: - -```html - - - -``` - -### Where should I put my global styles? - -Global styles should always be placed in their own stylesheet files whenever possible, and not in a Svelte component's ` -``` - -### Why can't `cssHash` be set in development mode? - -`cssHash` is fixed in development for CSS HMR in Svelte components, ensuring that the hash value is stable based on the file name so that styles are only updated when changed. - -However, `cssHash` is respected in production builds as HMR is a dev-only feature. - -### How do I add a Svelte preprocessor from a Vite plugin? - -You don't have to anymore. See [advanced usage](advanced-usage.md) for examples how to put transform hooks before or after Svelte preprocess or compile - -### What is going on with Vite and `Pre-bundling dependencies:`? - -Prebundling dependencies is an [optimization in Vite](https://vitejs.dev/guide/dep-pre-bundling.html). - -> We only use prebundling during **development**, the following does not apply to or describe the built application - -It is required for CJS dependencies, as Vite's development server only works with ES modules on the client side. -Importantly for Svelte libraries and ES modules, it also reduces the number of http requests when you load a page from the dev server and caches files so subsequent starts are even faster. - -The way prebundling Svelte libraries affects your dev-server load times depends on the import style you use, index or deep: - -#### Index imports - -Offers better DX but can cause noticable delays on your machine, especially for libraries with many files. - -```diff -import { SomeComponent } from 'some-library' -+ only one request per library -+ intellisense for the whole library after first import -- compiles the whole library even if you only use a few components -- slower build and dev-server ssr -``` - -#### Deep imports - -Offers snappier dev and faster builds for libraries with many files at the expense of some DX - -```diff -import SomeComponent from 'some-library/src/SomeComponent.svelte' -+ compiles only the components you import -+ faster build and dev-server ssr -- one request per import can slow down initial load if you use a lot of components -- intellisense only for imported components -``` - -#### Rewriting imports with plugins or preprocessors - -**Do not use it in combination with prebundling!** - -Prebundling works by reading your `.svelte` files from disk and scanning them for imports. It cannot detect -added/changed/removed imports and these then cause extra requests, delays and render the prebundled files from the initial scan moot. -If you prefer to use these tools, please exclude the libraries you use them with from prebundling. - -#### Excluding libraries from prebundling - -If you want to disable prebundling for a single library, use `optimizeDeps.exclude` - -```js -// vite.config.js -export default defineConfig({ - optimizeDeps: { - exclude: ['some-library'] // do not pre-bundle some-library - } -}); -``` - -Or disable it for all Svelte libraries - -```js -// svelte.config.js -export default { - vitePlugin: { - prebundleSvelteLibraries: false - } -}; -``` - -#### Recommendations - -There is no golden rule, but you can follow these recommendations: - -1. **Never** combine plugins or preprocessors that rewrite imports with prebundling -2. Start with index imports and if your dev-server or build process feels slow, run the process with `DEBUG="vite-plugin-svelte:stats"` to check compile stats to see if switching to deep imports can improve the experience. -3. Do not mix deep and index imports for the same library, use one style consistently. -4. Use different import styles for different libraries where it helps. E.g. deep imports for the few icons of that one huge icon library, but index import for the component library that is heavily used. - -#### I get a warning `Incompatible options: prebundleSvelteLibraries ...` - -This warning only occurs if you use non-default settings in your vite config that can cause problems in combination with prebundleSvelteLibraries. -You should not use prebundleSvelteLibraries during build or for ssr, disable one of the incompatible options to make that warning (and subsequent errors) go away. - -### how can I use vite-plugin-svelte from commonjs - -You really shouldn't. Svelte and Vite are esm first and the ecosystem is moving away from commonjs and so should you. Consider migrating to esm. - -In case you have to, you can rely on node's "require esm" feature available in v20.19+ - -```js -// vite.config.cjs -const { defineConfig } = require('vite'); -const { svelte, vitePreprocess } = require('@sveltejs/vite-plugin-svelte'); - -module.exports = defineConfig({ - plugins: [svelte({ preprocess: vitePreprocess() })] -}); -``` - - - -### missing exports condition - -> If you see a warning logged for this when using a Svelte library, please tell the library maintainers. - -Using the `svelte` field in `package.json` to point at `.svelte` source files is **deprecated** and you must use a `svelte` [export condition](https://nodejs.org/api/packages.html#conditional-exports). -vite-plugin-svelte 3 still resolves it as a fallback, but in a future major release this is going to be removed and without exports condition resolving the library is going to fail. - -Example: - -```diff -// package.json - "files": ["dist"], - "svelte": "dist/index.js", -+ "exports": { -+ ".": { -+ "svelte": "./dist/index.js" -+ } - } -``` - -You can also add individual exports of .svelte files in the exports map which gives users a choice to also use deep imports. -See the faq about [vite and prebundling](#what-is-going-on-with-vite-and-pre-bundling-dependencies) why they can be useful at times. - -> Library authors are highly encouraged to update their packages to add the new exports condition as outlined above. Check out -> [svelte-package](https://kit.svelte.dev/docs/packaging) which already supports it. -> -> For backwards compatibility, you can keep the `svelte` field in addition to the `exports` condition. But make sure that both always resolve to the same files. - -### How can I use relative paths for asset references in svelte components like `` - -This is not supported out of the box. To resolve assets, you have to either import them like this: - -```html - - -``` - -or use a separate tool to add this functionality. -The 2 recommended solutions are [sveltejs/enhanced-img](https://kit.svelte.dev/docs/images#sveltejs-enhanced-img) (only for image elements) and [svelte-preprocess-import-assets](https://www.npmjs.com/package/svelte-preprocess-import-assets) (for all asset URLs). diff --git a/docs/faq.md b/docs/faq.md new file mode 120000 index 000000000..6b575bba0 --- /dev/null +++ b/docs/faq.md @@ -0,0 +1 @@ +../documentation/docs/10-plugin/30-faq.md \ No newline at end of file diff --git a/docs/inspector.md b/docs/inspector.md deleted file mode 100644 index ce53d0396..000000000 --- a/docs/inspector.md +++ /dev/null @@ -1,129 +0,0 @@ -# Inspector - -`@sveltejs/vite-plugin-svelte-inspector` is a Vite plugin that adds a Svelte inspector in the browser. It shows the file location where the element under cursor is defined and you can click to quickly open your code editor at this location. - -Note that `@sveltejs/vite-plugin-svelte` needs to be installed as a peer dependency as the inspector brings in Svelte components to be compiled. - -## Setup - -### enable in Svelte config - -```js -// svelte.config.js -export default { - vitePlugin: { - inspector: true - } -}; -``` - -### enable with custom options in Svelte config - -```js -// svelte.config.js -export default { - vitePlugin: { - inspector: { - toggleKeyCombo: 'alt-x', - showToggleButton: 'always', - toggleButtonPos: 'bottom-right' - } - } -}; -``` - -### configure with environment variables - -Svelte Inspector toggle keys and other options are personal preferences. As such it isn't always convenient to define them in a shared svelte config file. -To allow you to use your own setup, svelte inspector can be configured via environment variables, both from shell and dotenv files. - -```shell -# just keycombo, unquoted string -SVELTE_INSPECTOR_TOGGLE=alt-x - -# options object as json -SVELTE_INSPECTOR_OPTIONS='{"holdMode": false, "toggleButtonPos": "bottom-left"}' - -# disable completely -SVELTE_INSPECTOR_OPTIONS=false - -# force default options -SVELTE_INSPECTOR_OPTIONS=true -``` - -> Inspector options set on the environment take precedence over values set in svelte config and automatically enable svelte inspector during dev. - -## Plugin options - -### toggleKeyCombo - -- **Type:** `string` -- **Default:** `'alt-x'` - - Define a key combo to toggle inspector. - - The value is recommended to be any number of modifiers (e.g. `control`, `shift`, `alt`, `meta`) followed by zero or one regular key, separated by `-`. Note that some keys have native behavior (e.g. `alt-s` opens history menu on firefox). - - Examples: `control-o`, `control-alt-s`, `meta-x`, `alt-i`. - -### navKeys - -- **Type:** `{ parent: string; child: string; next: string; prev: string }` -- **Default:** `{ parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' }` - - Define keys to select elements with via keyboard. This improves accessibility and helps selecting elements that do not have a hoverable surface area due to tight wrapping. - - `parent`: select closest parent - - `child`: select first child (or grandchild) - - `next`: next sibling (or parent if no next sibling exists) - - `prev`: previous sibling (or parent if no prev sibling exists) - -### openKey - -- **Type:** `string` -- **Default:** `'Enter'` - - Define key to open the editor for the currently selected dom node. - -### escapeKeys - -- **Type:** `string[]` -- **Default:** `['Backspace', 'Escape']` - - Define keys to close the inspector. - -### holdMode - -- **Type:** `boolean` -- **Default:** `true` - - Inspector will only open when the `toggleKeyCombo` is held down, and close when released. - -### showToggleButton - -- **Type:** `'always' | 'active' | 'never'` -- **Default:** `'active'` - - When to show the toggle button. The toggle button allows you to click on-screen to enable/disable the inspector, rather than using the `toggleKeyCombo`. - - `'always'`: always show the toggle button - - `'active'`: show the toggle button when the inspector is active - - `'never'`: never show the toggle button - -### toggleButtonPos - -- **Type:** `'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'` -- **Default:** `'top-right'` - - Where to display the toggle button. - -### customStyles - -- **Type:** `boolean` -- **Default:** `true` - - Inject custom styles when inspector is active. This is useful if you want to customize the inspector styles to match your app. - - When the inspector is active, the `svelte-inspector-enabled` class is added to the `body` element, and the `svelte-inspector-active-target` class is added to the current active target (e.g. via hover or keyboard). - -## Editors - -If your editor is not [supported out of the box](https://github.com/yyx990803/launch-editor#supported-editors), you can follow [the instructions here](https://github.com/yyx990803/launch-editor#custom-editor-support) to add it. diff --git a/docs/inspector.md b/docs/inspector.md new file mode 120000 index 000000000..6f241ecb0 --- /dev/null +++ b/docs/inspector.md @@ -0,0 +1 @@ +../documentation/docs/20-inspector/10-inspector.md \ No newline at end of file diff --git a/docs/preprocess.md b/docs/preprocess.md deleted file mode 100644 index 7c1dcb73d..000000000 --- a/docs/preprocess.md +++ /dev/null @@ -1,47 +0,0 @@ -# Preprocess - -`vite-plugin-svelte` also exports Vite preprocessors to preprocess Svelte components using Vite's built-in transformers. - -Compared to [`svelte-preprocess`](https://github.com/sveltejs/svelte-preprocess), Vite preprocessors share the same CSS configuration from the Vite config so you don't have to configure them twice. [`esbuild`](http://esbuild.github.io) can also be used to transform TypeScript. - -However, `svelte-preprocess` does provide extra functionalities not available with Vite preprocessors, such as [template tag](https://github.com/sveltejs/svelte-preprocess#template-tag), [external files](https://github.com/sveltejs/svelte-preprocess#external-files), and [global styles](https://github.com/sveltejs/svelte-preprocess#global-style) ([though it's recommended to use import instead](./faq.md#where-should-i-put-my-global-styles)). If those features are required, you can still use `svelte-preprocess`, but make sure to turn off it's script and style preprocessing options. - -## vitePreprocess - -- **Type:** `{ script?: boolean, style?: boolean | InlineConfig | ResolvedConfig }` -- **Default:** `{ script: false, style: true }` - - A Svelte preprocessor that supports transforming TypeScript, PostCSS, SCSS, Less, Stylus, and SugarSS. These are transformed when the script or style tags have the respective `lang` attribute. - - TypeScript: ` +
+ +``` + +Bad: + +```html + + + +
+``` + +## Why isn't Vite detecting my imports correctly in `.svelte` files with TypeScript? + +You have to use the `lang="ts"` attribute for Vite to parse it. Never `lang="typescript"` or `type="text/typescript"`. + +Good: + +```html + +``` + +Bad: + +```html + + + +``` + +## Where should I put my global styles? + +Global styles should always be placed in their own stylesheet files whenever possible, and not in a Svelte component's ` +``` + +## Why can't `cssHash` be set in development mode? + +`cssHash` is fixed in development for CSS HMR in Svelte components, ensuring that the hash value is stable based on the file name so that styles are only updated when changed. + +However, `cssHash` is respected in production builds as HMR is a dev-only feature. + +## How do I add a Svelte preprocessor from a Vite plugin? + +You don't have to anymore. See [advanced usage](advanced-usage.md) for examples how to put transform hooks before or after Svelte preprocess or compile + +## What is going on with Vite and `Pre-bundling dependencies:`? + +Prebundling dependencies is an [optimization in Vite](https://vitejs.dev/guide/dep-pre-bundling.html). + +> We only use prebundling during **development**, the following does not apply to or describe the built application + +It is required for CJS dependencies, as Vite's development server only works with ES modules on the client side. +Importantly for Svelte libraries and ES modules, it also reduces the number of http requests when you load a page from the dev server and caches files so subsequent starts are even faster. + +The way prebundling Svelte libraries affects your dev-server load times depends on the import style you use, index or deep: + +### Index imports + +Offers better DX but can cause noticable delays on your machine, especially for libraries with many files. + +```diff +import { SomeComponent } from 'some-library' ++ only one request per library ++ intellisense for the whole library after first import +- compiles the whole library even if you only use a few components +- slower build and dev-server ssr +``` + +### Deep imports + +Offers snappier dev and faster builds for libraries with many files at the expense of some DX + +```diff +import SomeComponent from 'some-library/src/SomeComponent.svelte' ++ compiles only the components you import ++ faster build and dev-server ssr +- one request per import can slow down initial load if you use a lot of components +- intellisense only for imported components +``` + +### Rewriting imports with plugins or preprocessors + +**Do not use it in combination with prebundling!** + +Prebundling works by reading your `.svelte` files from disk and scanning them for imports. It cannot detect +added/changed/removed imports and these then cause extra requests, delays and render the prebundled files from the initial scan moot. +If you prefer to use these tools, please exclude the libraries you use them with from prebundling. + +### Excluding libraries from prebundling + +If you want to disable prebundling for a single library, use `optimizeDeps.exclude` + +```js +// vite.config.js +export default defineConfig({ + optimizeDeps: { + exclude: ['some-library'] // do not pre-bundle some-library + } +}); +``` + +Or disable it for all Svelte libraries + +```js +// svelte.config.js +export default { + vitePlugin: { + prebundleSvelteLibraries: false + } +}; +``` + +### Recommendations + +There is no golden rule, but you can follow these recommendations: + +1. **Never** combine plugins or preprocessors that rewrite imports with prebundling +2. Start with index imports and if your dev-server or build process feels slow, run the process with `DEBUG="vite-plugin-svelte:stats"` to check compile stats to see if switching to deep imports can improve the experience. +3. Do not mix deep and index imports for the same library, use one style consistently. +4. Use different import styles for different libraries where it helps. E.g. deep imports for the few icons of that one huge icon library, but index import for the component library that is heavily used. + +### I get a warning `Incompatible options: prebundleSvelteLibraries ...` + +This warning only occurs if you use non-default settings in your vite config that can cause problems in combination with prebundleSvelteLibraries. +You should not use prebundleSvelteLibraries during build or for ssr, disable one of the incompatible options to make that warning (and subsequent errors) go away. + +## how can I use vite-plugin-svelte from commonjs + +You really shouldn't. Svelte and Vite are esm first and the ecosystem is moving away from commonjs and so should you. Consider migrating to esm. + +In case you have to, you can rely on node's "require esm" feature available in v20.19+ + +```js +// vite.config.cjs +const { defineConfig } = require('vite'); +const { svelte, vitePreprocess } = require('@sveltejs/vite-plugin-svelte'); + +module.exports = defineConfig({ + plugins: [svelte({ preprocess: vitePreprocess() })] +}); +``` + + + +## missing exports condition + +> If you see a warning logged for this when using a Svelte library, please tell the library maintainers. + +Using the `svelte` field in `package.json` to point at `.svelte` source files is **deprecated** and you must use a `svelte` [export condition](https://nodejs.org/api/packages.html#conditional-exports). +vite-plugin-svelte 3 still resolves it as a fallback, but in a future major release this is going to be removed and without exports condition resolving the library is going to fail. + +Example: + +```diff +// package.json + "files": ["dist"], + "svelte": "dist/index.js", ++ "exports": { ++ ".": { ++ "svelte": "./dist/index.js" ++ } + } +``` + +You can also add individual exports of .svelte files in the exports map which gives users a choice to also use deep imports. +See the faq about [vite and prebundling](#what-is-going-on-with-vite-and-pre-bundling-dependencies) why they can be useful at times. + +> Library authors are highly encouraged to update their packages to add the new exports condition as outlined above. Check out +> [svelte-package](https://kit.svelte.dev/docs/packaging) which already supports it. +> +> For backwards compatibility, you can keep the `svelte` field in addition to the `exports` condition. But make sure that both always resolve to the same files. + +## How can I use relative paths for asset references in svelte components like `` + +This is not supported out of the box. To resolve assets, you have to either import them like this: + +```html + + +``` + +or use a separate tool to add this functionality. +The 2 recommended solutions are [sveltejs/enhanced-img](https://kit.svelte.dev/docs/images#sveltejs-enhanced-img) (only for image elements) and [svelte-preprocess-import-assets](https://www.npmjs.com/package/svelte-preprocess-import-assets) (for all asset URLs). diff --git a/documentation/docs/10-plugin/index.md b/documentation/docs/10-plugin/index.md new file mode 100644 index 000000000..c18fc31d3 --- /dev/null +++ b/documentation/docs/10-plugin/index.md @@ -0,0 +1,3 @@ +--- +title: Plugin +--- diff --git a/documentation/docs/20-inspector/10-inspector.md b/documentation/docs/20-inspector/10-inspector.md new file mode 100644 index 000000000..83dc3010f --- /dev/null +++ b/documentation/docs/20-inspector/10-inspector.md @@ -0,0 +1,131 @@ +--- +title: Inspector +--- + +`@sveltejs/vite-plugin-svelte-inspector` is a Vite plugin that adds a Svelte inspector in the browser. It shows the file location where the element under cursor is defined and you can click to quickly open your code editor at this location. + +Note that `@sveltejs/vite-plugin-svelte` needs to be installed as a peer dependency as the inspector brings in Svelte components to be compiled. + +## Setup + +### enable in Svelte config + +```js +// svelte.config.js +export default { + vitePlugin: { + inspector: true + } +}; +``` + +### enable with custom options in Svelte config + +```js +// svelte.config.js +export default { + vitePlugin: { + inspector: { + toggleKeyCombo: 'alt-x', + showToggleButton: 'always', + toggleButtonPos: 'bottom-right' + } + } +}; +``` + +### configure with environment variables + +Svelte Inspector toggle keys and other options are personal preferences. As such it isn't always convenient to define them in a shared svelte config file. +To allow you to use your own setup, svelte inspector can be configured via environment variables, both from shell and dotenv files. + +```shell +# just keycombo, unquoted string +SVELTE_INSPECTOR_TOGGLE=alt-x + +# options object as json +SVELTE_INSPECTOR_OPTIONS='{"holdMode": false, "toggleButtonPos": "bottom-left"}' + +# disable completely +SVELTE_INSPECTOR_OPTIONS=false + +# force default options +SVELTE_INSPECTOR_OPTIONS=true +``` + +> Inspector options set on the environment take precedence over values set in svelte config and automatically enable svelte inspector during dev. + +## Plugin options + +### toggleKeyCombo + +- **Type:** `string` +- **Default:** `'alt-x'` + + Define a key combo to toggle inspector. + + The value is recommended to be any number of modifiers (e.g. `control`, `shift`, `alt`, `meta`) followed by zero or one regular key, separated by `-`. Note that some keys have native behavior (e.g. `alt-s` opens history menu on firefox). + + Examples: `control-o`, `control-alt-s`, `meta-x`, `alt-i`. + +### navKeys + +- **Type:** `{ parent: string; child: string; next: string; prev: string }` +- **Default:** `{ parent: 'ArrowUp', child: 'ArrowDown', next: 'ArrowRight', prev: 'ArrowLeft' }` + + Define keys to select elements with via keyboard. This improves accessibility and helps selecting elements that do not have a hoverable surface area due to tight wrapping. + - `parent`: select closest parent + - `child`: select first child (or grandchild) + - `next`: next sibling (or parent if no next sibling exists) + - `prev`: previous sibling (or parent if no prev sibling exists) + +### openKey + +- **Type:** `string` +- **Default:** `'Enter'` + + Define key to open the editor for the currently selected dom node. + +### escapeKeys + +- **Type:** `string[]` +- **Default:** `['Backspace', 'Escape']` + + Define keys to close the inspector. + +### holdMode + +- **Type:** `boolean` +- **Default:** `true` + + Inspector will only open when the `toggleKeyCombo` is held down, and close when released. + +### showToggleButton + +- **Type:** `'always' | 'active' | 'never'` +- **Default:** `'active'` + + When to show the toggle button. The toggle button allows you to click on-screen to enable/disable the inspector, rather than using the `toggleKeyCombo`. + - `'always'`: always show the toggle button + - `'active'`: show the toggle button when the inspector is active + - `'never'`: never show the toggle button + +### toggleButtonPos + +- **Type:** `'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'` +- **Default:** `'top-right'` + + Where to display the toggle button. + +### customStyles + +- **Type:** `boolean` +- **Default:** `true` + + Inject custom styles when inspector is active. This is useful if you want to customize the inspector styles to match your app. + + When the inspector is active, the `svelte-inspector-enabled` class is added to the `body` element, and the `svelte-inspector-active-target` class is added to the current active target (e.g. via hover or keyboard). + +## Editors + +If your editor is not [supported out of the box](https://github.com/yyx990803/launch-editor#supported-editors), you can follow [the instructions here](https://github.com/yyx990803/launch-editor#custom-editor-support) to add it. diff --git a/documentation/docs/20-inspector/index.md b/documentation/docs/20-inspector/index.md new file mode 100644 index 000000000..c18fc31d3 --- /dev/null +++ b/documentation/docs/20-inspector/index.md @@ -0,0 +1,3 @@ +--- +title: Plugin +--- diff --git a/documentation/docs/30-preprocess/10-preprocess.md b/documentation/docs/30-preprocess/10-preprocess.md new file mode 100644 index 000000000..6678cc8a1 --- /dev/null +++ b/documentation/docs/30-preprocess/10-preprocess.md @@ -0,0 +1,49 @@ +--- +title: Preprocess +--- + +`vite-plugin-svelte` also exports Vite preprocessors to preprocess Svelte components using Vite's built-in transformers. + +Compared to [`svelte-preprocess`](https://github.com/sveltejs/svelte-preprocess), Vite preprocessors share the same CSS configuration from the Vite config so you don't have to configure them twice. [`esbuild`](http://esbuild.github.io) can also be used to transform TypeScript. + +However, `svelte-preprocess` does provide extra functionalities not available with Vite preprocessors, such as [template tag](https://github.com/sveltejs/svelte-preprocess#template-tag), [external files](https://github.com/sveltejs/svelte-preprocess#external-files), and [global styles](https://github.com/sveltejs/svelte-preprocess#global-style) ([though it's recommended to use import instead](./faq.md#where-should-i-put-my-global-styles)). If those features are required, you can still use `svelte-preprocess`, but make sure to turn off it's script and style preprocessing options. + +## vitePreprocess + +- **Type:** `{ script?: boolean, style?: boolean | InlineConfig | ResolvedConfig }` +- **Default:** `{ script: false, style: true }` + + A Svelte preprocessor that supports transforming TypeScript, PostCSS, SCSS, Less, Stylus, and SugarSS. These are transformed when the script or style tags have the respective `lang` attribute. + - TypeScript: `