Creating a Sveltekit-Capacitor app
2023-01-15I want to see if I can find a peaceful workflow using SvelteKit for mobile apps. The key things I want is ability to have some form of hot module reloading when I’m building. SvelteKit might seem like the wrong fit since it is built with the intention of being used for SSR, edge functions, and really working with the web. However, the SvelteKit docs do mention that you can get SPA-like client rendered behaviour with some configuration adjustments.
Instructions
First create a new folder for the project.
Lets first start with generating a sveltekit app
npm create svelte@latest my-app
cd my-app
pnpm install
Next we are going to enforce that the app is built similar to a SPA where we don’t expect it to have server side rendering.
Use @sveltejs/adapter-static
import adapter from '@sveltejs/adapter-static`;
kit: {
adapter: adapter({
fallback: 'index.html'
})
}
Enforce SPA mode
Add the following in the root +layout.svelte
export const ssr = false
Add Capacitor
Basically just followed the “Getting Started” instructions on the capacitor website.
Install capacitor
pnpm install @capacitor/core
pnpm install -D @capacitor/cli
Initialize the capacitor config
npx cap init
Create the android and projects. I didn’t do try ios , maybe at a later date I’ll look into it, but the process seems simlar.
pnpm intall @capacitor/android @capacitor/ios
npx cap add android
Install android studio
Note, that if you’re on Windows and you are doing this in WSL, you will have to install openjdk and android studio into wsl. I tried this..and it worked, but it also felt very clumsy and slow, so I ended up setting up my development on just plain ol’ Windows.
Test if it runs
At this point you should be able to get it running in Android Studio.
To run the latest build you’ll have to run the following:
npx cap sync
This will sync up the .android folder with the latest code.
Finally, open the project in Android studio by importing the android/ directory or by using the following command
npx cap open android
Hot module reloading
I really like hot module reloading. I just like the iteration cycle when having it available, and it is still possible. It seems like it is still possible though by adding the server config into capacitor.config.ts , and point the url property to the url provided when you run the sveltekit dev server using the --host tag. (ex. pnpm run dev --host ).
server: {
url: '<url of dev server>',
'cleartext': true
}
I cannot confirm yet though if all the functionality is still available if I do it this way, but so far the app loads and hot module reloading works .
Conclusion
It seems to work. I’ll likely run into some restrictions or issues I’m sure, but for now, its a low overhead option for me to build simple Android apps without having to change my workflow much.