Skip to content

Instantly share code, notes, and snippets.

@wiverson
Last active January 18, 2024 19:53
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wiverson/b60f905f76d5a581d682204c0afd84f3 to your computer and use it in GitHub Desktop.
Save wiverson/b60f905f76d5a581d682204c0afd84f3 to your computer and use it in GitHub Desktop.

Steps to get Capacitor working with SvelteKit

  1. Set up a SvelteKit project as usual.
npm create svelte@latest my-app
cd my-app
npm install
npm run dev -- --open
  1. Set it to render with SvelteKit's static adapter in SPA mode instead of auto.

You want SPA like behavior in this case (you don't care about SEO in a mobile app) so set the SPA-like configuration via fallback: 'error.html' in the adapter config.

To ensure SPA like behavior throughout the app, you should also set:

// src/routes/+layout.js

export const ssr = false;

...as documented in the SvelteKit docs. (Thanks Tommertom!)

  1. Add Capacitor to the Svelte project, but instead of pointing Capacitor at a public directory you want to use build instead:
npm install @capacitor/core @capacitor/cli
npx cap init [name] [id] --web-dir=build

For the id, use the app identifier (e.g. com.example.myapp).

From here on, you can use standard Capacitor workflow commands.

Geolocation Demo

The Capacitor Svelte demo shows a Svelte component that accesses Geolocation. To get that to work, you will still have to install the Geolocation plugin and add iOS and Android flags.

Hot Reload

Finally, if you want to enable hot-reload in the simulator you can crib off of this project.

The main thing is setting Capacitor to point to a local server to load content instead of static files. Unfortunately AKAIK you have to manually tweak the Capacitor config file to turn the server on for dev and off for production builds.

In the package.json you can see that the project is using run-p to both start the vite dev server and also run Capacitor in parallel.

If you want to accomplish something similar without adding all of those commands to your package.json you can do the following (or similar):

  1. Update the capacitor config to point to the desired server and local host.
  2. Run the dev server in one terminal
  3. Run cap sync ios and then cap run ios in another Terminal (and/or android)

Of course, you can also add npm run commands to make this easier and be cool like drannex42. :)

So far this all seems to be working fine as of 10/13/2022.

Tips

You may want to turn off the double-tap-to-zoom feature in Safari Mobile.

If you turn on the Develop menu in Safari you can debug the Simulator Safari.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment