Other resources permalink
Please see the Svelte FAQ and vite-plugin-svelte
FAQ as well for the answers to questions deriving from those libraries.
Please see the Svelte FAQ and vite-plugin-svelte
FAQ as well for the answers to questions deriving from those libraries.
SvelteKit is currently in beta while we finalize the APIs. No new features will be added to Sapper and all development will be focused on SvelteKit.
SvelteKit has HMR enabled by default powered by svelte-hmr. If you saw Rich's presentation at the 2020 Svelte Summit, you may have seen a more powerful-looking version of HMR presented. This demo had svelte-hmr
's preserveLocalState
flag on. This flag is now off by default because it may lead to unexpected behaviour and edge cases. But don't worry, you are still getting HMR with SvelteKit! If you'd like to preserve local state you can use the @hmr:keep
or @hmr:keep-all
directives as documented on the svelte-hmr page.
Please make sure the version of the adapter specified in your package.json
is "next"
.
Aliases can be set in svelte.config.js
as described in the configuration
docs.
Then run npm run sync
or npm run dev
(which will execute sync
). SvelteKit will automatically generate the required alias configuration in jsconfig.json
or tsconfig.json
.
Vite uses dotenv to load environment variables from a file named .env
or similar. Only environment variables prefixed with VITE_
are exposed (you can set envPrefix
to change this). You can access the variable using import.meta.env.VITE_ENV_VAR
, and Vite will statically replace them at build-time.
To use environment variables at runtime, you would need to instantiate dotenv yourself in your server-side code so that they are exposed at process.env.YOUR_ENV_VAR
. You may also use $session
to pass them to the client if needed.
Please see the Vite documentation for more info about environment variables.
You cannot directly require JSON files, since SvelteKit expects svelte.config.js
to be an ES module. If you'd like to include your application's version number or other information from package.json
in your application, you can load JSON like so:
ts
import {readFileSync } from 'fs';import {fileURLToPath } from 'url';constfile =fileURLToPath (newURL ('package.json', import.meta.url ));constjson =readFileSync (file , 'utf8');constpkg =JSON .parse (json );
Vite's SSR support has become fairly stable since Vite 2.7. Most issues related to including a library are due to incorrect packaging.
Libraries work best with Vite when they distribute an ESM version and you may wish to suggest this to library authors. Here are a few things to keep in mind when checking if a library is packaged correctly:
exports
takes precedence over the other entry point fields such as main
and module
. Adding an exports
field may not be backwards-compatible as it prevents deep imports..mjs
unless "type": "module"
is set in which any case CommonJS files should end with .cjs
.main
should be defined if exports
is not. It should be either a CommonJS or ESM file and adhere to the previous bullet. If a module
field is defined, it should refer to an ESM file.svelte
field defining the entry point.It is encouraged to make sure the dependencies of external Svelte components provide an ESM version. However, in order to handle CommonJS dependencies vite-plugin-svelte
will look for any CJS dependencies of external Svelte components and ask Vite to pre-bundle them by automatically adding them to Vite's optimizeDeps.include
which will use esbuild
to convert them to ESM. A side effect of this approach is that it takes longer to load the initial page. If this becomes noticable, try setting experimental.prebundleSvelteLibraries: true in svelte.config.js
. Note that this option is experimental.
If you are still encountering issues we recommend checking the list of known Vite issues most commonly affecting SvelteKit users and searching both the Vite issue tracker and the issue tracker of the library in question. Sometimes issues can be worked around by fiddling with the optimizeDeps
or ssr
config values.
Make sure you've read the documentation section on integrations. If you're still having trouble, solutions to common issues are listed below.
Put the code to query your database in endpoints - don't query the database in .svelte files. You can create a db.js
or similar that sets up a connection immediately and makes the client accessible throughout the app as a singleton. You can execute any one-time setup code in hooks.js
and import your database helpers into any endpoint that needs them.
adapter-node
builds a middleware that you can use with your own server for production mode. In dev, you can add middleware to Vite by using a Vite plugin. For example:
ts
/** @type {import('vite').Plugin} */constmyPlugin = {name : 'log-request-middleware',configureServer (server ) {server .middlewares .use ((req ,res ,next ) => {console .log (`Got request ${req .url }`);next ();});}};constconfig = {kit : {vite : {plugins : [myPlugin ]}}};export defaultconfig ;
See Vite's configureServer
docs for more details including how to control ordering.
document
or window
?permalinkIf you need access to the document
or window
variables or otherwise need code to run only on the client-side you can wrap it in a browser
check:
ts
import {browser } from '$app/env';if (browser ) {// client-only code here}
You can also run code in onMount
if you'd like to run it after the component has been first rendered to the DOM:
ts
import {onMount } from 'svelte';onMount (async () => {const {method } = await import('some-browser-only-library');method ('hello world');});
If the library you'd like to use is side-effect free you can also statically import it and it will be tree-shaken out in the server-side build where onMount
will be automatically replaced with a no-op:
ts
import {onMount } from 'svelte';import {method } from 'some-browser-only-library';onMount (() => {method ('hello world');});
Otherwise, if the library has side effects and you'd still prefer to use static imports, check out vite-plugin-iso-import to support the ?client
import suffix. The import will be stripped out in SSR builds. However, note that you will lose the ability to use VS Code Intellisense if you use this method.
ts
import {onMount } from 'svelte';import {method } from 'some-browser-only-library?client';onMount (() => {method ('hello world');});
Sort of. The Plug'n'Play feature, aka 'pnp', is broken (it deviates from the Node module resolution algorithm, and doesn't yet work with native JavaScript modules which SvelteKit — along with an increasing number of packages — uses). You can use nodeLinker: 'node-modules'
in your .yarnrc.yml
file to disable pnp, but it's probably easier to just use npm or pnpm, which is similarly fast and efficient but without the compatibility headaches.
Currently ESM Support within the latest Yarn (version 3) is considered experimental.
The below seems to work although your results may vary.
First create a new application:
yarn create svelte myapp
cd myapp
And enable Yarn Berry:
yarn set version berry
yarn install
Yarn 3 global cache
One of the more interesting features of Yarn Berry is the ability to have a single global cache for packages, instead of having multiple copies for each project on the disk. However, setting enableGlobalCache
to true causes building to fail, so it is recommended to add the following to the .yarnrc.yml
file:
nodeLinker: node-modules
This will cause packages to be downloaded into a local node_modules directory but avoids the above problem and is your best bet for using version 3 of Yarn at this point in time.
See also the Svelte FAQ for questions relating to Svelte directly.