GithubHelp home page GithubHelp logo

drannex42 / svelte-capacitor Goto Github PK

View Code? Open in Web Editor NEW
370.0 19.0 33.0 121 KB

Build hybrid mobile apps using Svelte and CapacitorJS with live reloading on Android and iOS!

License: MIT License

HTML 50.90% Svelte 13.40% TypeScript 35.70%
svelte-v3 svelte capacitor javascript capacitor-android capacitor-ios android cordova

svelte-capacitor's Introduction

Svelte + Capacitor (w/ live reload) Template

This is a project template for Svelte + CapacitorJS apps with live reload, granting the ability to quickly build production ready applications for iOS and Android at near-native performance using JavaScript (Svelte).

Changelog

v2.0.0 - The new version is here, this comes with some better defaults, vite as the build manager, built in routing library, TypeScript, and aliases. While this could be seen as an 'incremental' update I think this works as a v2.0.0 as it was a complete rewrite.

  • Build Tool: Changed the build tool to Vite from Rollup, this is the new and recommended way to develop Svelte applications, it's faster, cleaner, and easier to handle.
  • Routing: Built in routing library, using Routify, I spent a considerable time debating on including one - I decided I would. This is mainly due to the amount of messages and emails(!) I received asking how to implement one, Routify is by far my favorite and so here it is. This is very easily removed and replaced with your preferred.
  • Typescript: I personally do not use typescript as much as I should, but others do. I have included some TS configs for you.
  • @components, @store, and @utils: If you have ever taken a look at sveltekit they have these nifty aliases throughout their code so you don't have to write '../../../components' or what have you. Now you can just do '@components/file' and Vite will readily load them from the components folder, this makes it easy to create changes as you don't need to change the file location on every move or copy. Please check out the Vite Aliases package for more questions.

Setup

Note that you will need to have Node.js installed.

Get started

Install the dependencies...

git clone "https://github.com/drannex42/svelte-capacitor.git"
cd svelte-capacitor
npm install

Run local dev server (no capacitor)

npm run dev:start

Add your Capacitor platform

npx cap add android // (or ios)

Run local dev server (with capacitor)

Please see section below (Develop on your device with livereload)

Develop on your device with livereload (hot reload)

If you're only targeting Android, you only need to change the server.url section in capacitor.config.json to use http://10.0.2.2:5001, since Android Studio already adds a localhost proxy. Just remember to remove it when building your app for production.

If you're targeting iOS or both, you will need to append your workstation IP to the server.url section in capacitor.config.json instead. To discover your workstation IP, just run ifconfig or find it on the network settings.

Tip: Remember you will need the http:// before the server IP.

Back in the root folder:

npm run dev:android or npm run dev:ios

This will run the capacitor/svelte project with a web view pointing to your workstation's IP. You should see the message Welcome to Svelte! if svelte loaded correctly.

Try to change something in App.svelte, and you should see the content reload on your device.

  • You need to have an emulator/device connected to adb
  • Your device has to be connected to the same wifi network as your workstation.

Change Splash screen and app icon:

  • Add icon.png and splash.png to resources dir
  • Recomended size:
    • Icon - 512x512
    • Splash - 1920x1920
  • Next, run the following to generate all images then copy them into the native projects:
cordova-res ios --skip-config --copy
cordova-res android --skip-config --copy

To build a production application:

Remember to remove the server.url in capacitor.config.json

npm run build:android or npm run build:ios

Quick Tips

Developer Tools

You can use any Chromium-based browser and use their Developer Tools (for Android atleast, have not tested iOS) to debug and access console commands on your personal device, by going to chrome://inspect#devices., edge://inspect#devices., vivaldi://inspect#devices., brave://inspect#devices, &c.

The standard web inspector will also work for debugging and rewriting styling and html without using your IDE just like when building a normal website. This may have some issues with some forms of SVG-related svelte templating (I have had issues with using some chart libraries displaying in the web inspector), they will still show up on the device but not in the preview.

You may use the address bar in the developer tools to navigate to direct views in your application, even without any tappable links to do so. This allows you to create hidden routes for testing.

Assets

Place any assets, CSS, client JS, Images in the assets folder - not the public folder! On build and usage this will add everything to the public dist folder for copying to the device application. See Vite.js on this settings.

Aliases

@components, @store, and @utils: If you have ever taken a look at sveltekit they have these nify aliases throughout their code so you don't have to write '../../../components' or what have you. Now you can just do '@components/file' and Vite will readily load them from the components folder, this makes it easy to create changes as you don't need to change the file location on every move or copy. Please check out the Vite Aliases package for more questions.

Routing Libraries

Since this is a Svelte application you will be able to use any routing manager that you prefer. I prefer routify, but others such as the following will work as well (Routify is built into this project, but easily changed)

Accessing Device APIs

CapacitorJS is/was based on Cordova and has complete backwards compatibility with cordova plugins. To find plugins that allow you to access the device api's easier, attempt to find cordova or capacitor plugins. You will need to view their (capacitorjs) docs to learn how to properly accesss those.

Why didn't the second version use Sveltekit?

This is ready for production (this template is being used in several production applications already!) and Sveltekit is not, I also believe this is much more easily extensible and doesn't lock you into the Sveltekit way of doing things (no opinionated API's) while adding in defaults for Capacitor.js for application development on Android and iOS. You likely don't need to learn a new paradigm, just use what you know with Javascript and Svelte to build cross platform applications at near native performance.

Find a bug? Want to add a feature?

Submit a PR! I would love to have more people working on this, the advantages of a system such as this vs NativeScript or React Native are innumerable especially in regards for how quickly you can get started and instant developer options and this could be built out to something great!

Are you using this project! Let us know!

I would love to keep a collection of all the projects using this!


This template was created by Drannex42 (Macleod Sawyer) of DNX Industries - Source can be found here

svelte-capacitor's People

Contributors

ak4zh avatar didier avatar drannex42 avatar lucianoratamero avatar neorth avatar omgimalexis avatar sdesya74 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

svelte-capacitor's Issues

How do I run Electron?

How do I run Electron?
There is nothing mentioned in package.json.
Edit:
I managed to run electron using.
npx cap open electron.
but I see only a blank page.

Configure vite to watch assets

Vite watches the source files but does not watch assets. Would be nice to save a global css file and have it refresh automatically like Svelte does with rollup (at least the way it's configured standard). I tried to do this myself but this is my first time using Vite and I'm not really sure how it works.

Great little template by the way! Thanks for sharing.

Script in package.json has wrong command

Simple typo here:

"cap-run:ios": "cap sync ios && cap open android",

Should read "cap-run:ios": "cap sync ios && cap open ios" instead.

Error output when running a new repo using svelte-capacitor as a template:

 ~/projects/poker-session-tracker-ios[master]$ npm run dev:ios

> [email protected] dev:ios
> run-p dev:start cap-run:ios


> [email protected] dev:start
> run-p build:routify dev:vite


> [email protected] cap-run:ios
> cap sync ios && cap open android

✔ Copying web assets from public to ios/App/App/public in 4.09ms
✔ Creating capacitor.config.json in ios/App/App in 625.33μp
✔ copy ios in 10.00ms
✔ Updating iOS plugins in 1.30ms
⠙ Updating iOS native dependencies with pod install
> [email protected] dev:vite
> vite --host --port 5000


> [email protected] build:routify
> routify

⠼ Updating iOS native dependencies with pod install [Routify] Watching src/pages

  vite v2.4.3 dev server running at:

  > Local:    http://localhost:5000/
  > Network:  http://192.168.2.3:5000/

  ready in 164ms.

✔ Updating iOS native dependencies with pod install in 2.76s
✔ update ios in 2.77s
[info] Sync finished in 2.784s
[error] android platform has not been added yet.
        See the docs for adding the android platform: https://capacitorjs.com/docs/android#adding-the-android-platform
ERROR: "cap-run:ios" exited with 1.

Include example of how to integrate with routify

This is a very cool project template, very easy to get running. Thanks for putting it together and sharing it!

For those of us that struggle a bit with how to configure and setup things it would be great if you could include an example of how to integrate routify into the template. When I tried the most straight forward way from the routify docs I ended up with a "Error: UMD and IIFE output formats are not supported for code-splitting builds." error.

Error when trying to build for IOS

Running the command
npm run build:ios

I get the following error

[error] Could not find the web assets directory: ./www.
        Please create it and make sure it has an index.html file. You can change the path of this directory in
        capacitor.config.json (webDir option). You may need to compile the web assets for your app (typically npm run
        build). More info: https://capacitorjs.com/docs/basics/workflow#sync-your-project

however, in my capacitor.config.json the webDir field is set to /public.

{
  "appId": "com.svelte.capacitor",
  "appName": "Svelte Capacitor",
  "bundledWebRuntime": false,
  "npmClient": "npm",
  "webDir": "public",
  "plugins": {
    "SplashScreen": {
      "launchShowDuration": 0
    }
  },
  "cordova": {},
  "server": {
    // "url": "http://192.168.2.3:5000",
    "cleartext": true
  }
}

Not sure what to do here

dev:ios does not hot reload nor rebuild app on simulator

In previous version, running npm run dev:ios would launch servers on port 5000 and 5001 and allow ios simulator to hot reload content when you make changes to source code, same as you would get on a local web browser.

In this new version, running npm run dev:ios and running the simulator will load the app, but any changes to source code does nothing on the simulator - code changes do not appear, even if on web browser changes are reflected immediately (ie: I have local web browser running my svelte page as well as the Xcode ios simulator - changes appear on the web browser but not on the IOS).

In fact, even stopping and restarting npm run dev:ios does not update changes on the ios simulator. No changes are reflected until you type npm run build:ios

In the previous version, the package.json scripts included running a server on port 5000 as well as another server on port 5001. In this version, I only see script that runs vite on port 5000. However, in the capacitor.config.json the server has the line "url": "http://change-me:5001" - but I notice nothing running on port 5001 in the package.json scripts.

Xcode log output from previous version:

Loading network plugin
2021-07-22 11:32:00.294465-0400 App[84477:30412126] CAPKeyboard: resize mode - native
⚡️  Loading app at http://192.168.2.3:5001...
2021-07-22 11:32:00.385756-0400 App[84477:30412126] WF: === Starting WebFilter logging for process App
2021-07-22 11:32:00.385873-0400 App[84477:30412126] WF: _userSettingsForUser : (null)
2021-07-22 11:32:00.385929-0400 App[84477:30412126] WF: _WebFilterIsActive returning: NO
APP ACTIVE
Reachable via WiFi
⚡️  WebView loaded
⚡️  WebView loaded

Xcode log out from v2.0:

2021-07-22 11:22:54.420398-0400 App[83598:30400636] DiskCookieStorage changing policy from 2 to 0, cookie file: file:///Users/tajima/Library/Developer/CoreSimulator/Devices/901D5A60-1082-4B25-9130-029983B267AA/data/Containers/Data/Application/9BA8AC23-9CAD-4A59-B122-E81DF7591159/Library/Cookies/com.svelte.capacitor.binarycookies
⚡️  Loading app at capacitor://localhost...
2021-07-22 11:22:54.635729-0400 App[83598:30400636] WF: === Starting WebFilter logging for process App
2021-07-22 11:22:54.635796-0400 App[83598:30400636] WF: _userSettingsForUser : (null)
2021-07-22 11:22:54.635854-0400 App[83598:30400636] WF: _WebFilterIsActive returning: NO
⚡️  WebView loaded

My capacitor.config.json:

{
	"appId": "com.svelte.capacitor",
	"appName": "Svelte Capacitor",
	"bundledWebRuntime": false,
	"npmClient": "npm",
	"webDir": "public",
	"plugins": {
		"SplashScreen": {
			"launchShowDuration": 0
		}
	},
	"cordova": {},
	"server": {
		"server": {
			"url": "http://192.168.2.3:5001",
			"cleartext": true
		}
	}
}

The only thing changed was I added my ip in the server part.

Not sure if I am doing something wrong, or something is not configured properly, for if there is a script missing from package.json?

Public apps using this template?

Does anyone have something published to Android store using this template? Really curious to try out something actively using this.

Cheers!

Add Electron Support

This was in the very first version and it was beyond buggy. I removed it. This is an official issue to get it sorted out.

I have a barely working version, but it requires some serious modifications to the electron build system, so I am not particularly proud of it.

If anyone has any ideas, please submit them here!

Vite error when using TypeScript inside .svelte components

Hello, I came across this template on reddit and decided to try it out. I use TypeScript for everything, so I also use it inside svelte components. Now, here's the issue I came across:

When I change the <script> tag in a .svelte file to <script lang='ts'> and then use a TypeScript syntax (for example type annotations), vite throws an error:

2:41:01 PM [vite] Internal server error: Unexpected token
  Plugin: vite-plugin-svelte
  File: /home/user/Documents/Projects/svelte-capacitor/src/pages/index.svelte
  1: <script lang="ts">
  2:     var name: string = 'svelte'
                 ^
  3:     var image = "assets/svelte_cap.png"
  4: </script>
      at error (/home/user/Documents/Projects/svelte-capacitor/node_modules/svelte/compiler.js:17701:20)
      at Parser$1.error (/home/user/Documents/Projects/svelte-capacitor/node_modules/svelte/compiler.js:17777:10)
      at Parser$1.acorn_error (/home/user/Documents/Projects/svelte-capacitor/node_modules/svelte/compiler.js:17771:15)
      at Object.read_script [as read] (/home/user/Documents/Projects/svelte-capacitor/node_modules/svelte/compiler.js:8469:17)
      at tag (/home/user/Documents/Projects/svelte-capacitor/node_modules/svelte/compiler.js:16860:34)
      at new Parser$1 (/home/user/Documents/Projects/svelte-capacitor/node_modules/svelte/compiler.js:17736:22)
      at parse$3 (/home/user/Documents/Projects/svelte-capacitor/node_modules/svelte/compiler.js:17868:21)
      at compile (/home/user/Documents/Projects/svelte-capacitor/node_modules/svelte/compiler.js:31282:18)
      at compileSvelte (/home/user/Documents/Projects/svelte-capacitor/node_modules/@sveltejs/vite-plugin-svelte/dist/index.cjs:302:48)
      at async TransformContext.transform (/home/user/Documents/Projects/svelte-capacitor/node_modules/@sveltejs/vite-plugin-svelte/dist/index.cjs:1150:27)

How to reproduce:

  • Clone this repository
  • Run npm install
  • Change <script> tag to <script lang='ts'> in index.svelte
  • Change var name = 'svelte' tag to var name: string = 'svelte' in index.svelte
  • Run npm run dev:start
  • Browse to http://localhost:5000/

Does anyone know how to fix this? Is this the expected behaviour or a bug? I'd be happy to provide a PR when I/we find a solution.
Thank you and have a nice day :)

Error / warning in Chrome DevTools

Hi! I'm trying the template and I noted something like the following in dev tools console panel.

image

The output of the console where I run npm run dev:start also says:

[svelte-preprocess] Deprecation notice: using 'lang="typescript"' is no longer recommended and will be removed in the next major version. Please use 'lang="ts"' instead.
10:05:08 AM [vite-plugin-svelte] /home/paolo/svelte-capacitor/src/App.svelte:9:1 No scopable elements found in template. If you're using global styles in the style tag, you should move it into an external stylesheet file and import it in JS. See https://github.com/sveltejs/vite-plugin-svelte/blob/main/docs/faq.md#where-should-i-put-my-global-styles.

10:05:08 AM [vite] hmr update /src/App.svelte
10:05:08 AM [vite-plugin-svelte] /home/paolo/svelte-capacitor/src/pages/index.svelte:7:4 A11y: element should have an alt attribute

files in the public directory are served at the root path.
Instead of /assets/favicon/site.webmanifest, use /favicon/site.webmanifest.

Is it something worth a fix?

Behind on Vite - Unable to resolve dependency tree

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/vite
npm ERR!   dev vite@"^2.2.3" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer vite@"^3.0.0" from @sveltejs/[email protected]
npm ERR! node_modules/@sveltejs/vite-plugin-svelte
npm ERR!   dev @sveltejs/vite-plugin-svelte@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /Users/oliverdixon/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/oliverdixon/.npm/_logs/2022-08-10T11_33_32_669Z-debug-0.log

tvOS

is building tvOS and/or watchOS apps possible?

Update rollup configs and versions to sync changes with svelte/template

Hello, awesome svelters o/

When testing this project, I found out a couple of things that would be nice to change :]

The first one is: since last November, with rollup-plugin-svelte's v7, the svelte plugin for rollup offloads CSS handling to rollup by default.
That means that, if we were to use new versions of the rollup-plugin-svelte, the build CSS file would not be created. :/

To fix that, and to sync up the changes from svelte/template, we could offload CSS to another plugin.
svelte/template uses rollup-plugin-css-only for that.

I already have all updates working on a test app locally, so I could open a PR, if you want :]
I found out another issue (and possible fix), so I'll be opening another discussion as well.

As always, thanks for the hard work!

Vite fails to start server - Failed to resolve entry for package "@roxi/routify > @types/node"

I cloned the template

npm i
npm run dev:start

Error: Failed to resolve entry for package "@roxi/routify > @types/node". The package may have incorrect main/module/exports specified in its package.json: 
Failed to resolve entry for package "@roxi/routify > @types/node". The package may have incorrect main/module/exports specified in its package.json.

I have checked for possible issues reported in the vite repo & routify repo and found none.
Can you confirm if this is not a problem with the config in this template and possibly point me to a resolution ?

"If you're targeting iOS or both" readme instruction.

If you're targeting iOS or both, you will need to append your workstation IP to the server.url section in capacitor.config.json instead.

What does this look like for example? There's a lot of ways that "append" here could work.

Use `http://10.0.2.2:5001` as server URL alternative for android development

Related to: #5

Hi again!

After digging up a bit more about Android development, I found out that Android Studio adds 10.0.2.2 as a proxy to 127.0.0.1.
That means that, if you're only targeting Android (as I am), you wouldn't need to configure anything at all on capacitor.config.json to enable live reloading. I've tested it locally and works beautifully. :]

I'm thinking about adding a couple of comments on capacitor.config.json and README.md to make things easier for Andoid devs.
Woking on a PR right now, but feel free to reject it if you don't think it's a good idea!

Issues setting up livereload

Hello again o/
I'm a bit of a noob on the mobile dev space, so if this issue doesn't make sense, please let me know!

When testing this project, everything worked beautifully, but I discovered that livereload didn't seem to work out of the box.
The livereload script always sent a Failed to load resource: net::ERR_CONNECTION_REFUSED error on the network tab when I was debugging the app, and refused to be loaded.
It works fine when accessing the app via browser, though so it was really weird.

After digging up a bit on capacitor's docs, I found that the integration with non-ionic apps is kind of manual.
I'm guessing that this was the reason for the need to pass the url key on the capacitor.config.json file.
It wasn't clear to me, though, which URL I should put there.

Then, after a bit of fiddling, I understood that I should've been passing the sirv URL (started up by npm run serve:capacitor) instead of the URL generated by npm run autobuild.
But since they both run servers, and autobuild starts up faster than serve:capacitor on my PC, when serve:capacitor starts, it assigns itself a random port to run (always around 35000).
And that means I can't really know which port it will run at, so I could put it on my url config for capacitor.

(phew)

So, what I did locally was to add a --port 5001 arg to the serve:capacitor npm script (to make it static), then find out my local IP with ifconfig, and finally set up the url setting with http://my-local-ip:5001.
With that, livereload started working again. 🎉

My suggestions about this issue would be to:

  • add the --port 5001 to the serve:capacitor npm script;
  • change the default url key to use 5001 instead of PORT;
  • and improve the docs a bit to make it a bit clearer on what's going on, and why setting up your local IP is needed to set up livereload.

As always, I'd be glad to open a PR for that, and thanks for the hard work!

[Question] Using https with live reload

Hello,
I'm not directly using this template but since you guys say it's production ready, I'd like to ask for advice on how to use https with the live reload functionality.
I need https because I'm using auth0 libs, which will throw when window.crypto.subtle is undefined (due to not being on a secure origin).
I set server.https: true in vite.config.ts.
Then I tried all possible flags in ionic cap run android to no avail. If I use --livereload-url=https://192.168.1.245:3000, the Android webview says it cannot load due to a net error. The html is empty and the network tab in Chrome devtools shows no traffic at all when reloading.
I'm out of ideas. I can ofc develop on the web and just bundle the android/ios final apps, 99% of the things should be the same, but even for small functionalities it's very time consuming to rerun cap run android every time, when you don't have live reload...
Thanks in advance and thanks for this template which served as inspiration! 👍

npm build:app does not put assets in /public/assets folder

While trying to get ios simulator working, I noticed that the script build:app does not move the assets in /assets into the /public/assets folder, it puts them into /public.

I notice this because the script build:ios calls build:app first before copying into the /ios/App/App folder. But when running the IOS simulator, I noticed that the svelte_cap.png would not load on the simulator, because it is referencing /assets/svelte_cap.png but that file is actually in ios/App/App/public/svelte_cap.png.

I'm not sure what the expected behaviour is supposed to be, but I am thinking it's a problem in the build:app stage?

I also notice that following the readme guide for running on ios, npm run dev:ios initially presents a blank screen on the simulator. Nothing appear. If I build the app first npm run build:ios and then run npm run dev:ios I can at least see the screen - however no hot reloading works - which makes me believe that npm run build:ios is not the required step and that the ios simulator should of worked properly with just the npm run dev:ios command. (This is how I first noticed that the assets weren't being copied into the /assets folder.)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.