I'm trying to start a colyseus app using Svelte.
I am import colyseus using:
import { Client } from 'colyseus.js'
This builds fine but gives me the following messages when running the app:
Creating a browser bundle that depends on "https", "http" and "url". You might need to include https://github.com/snowpackjs/rollup-plugin-polyfill-node
- @colyseus/schema
LiveReload enabled
(!) Missing global variable names
Use output.globals to specify browser global variable names corresponding to external modules
https (guessing 'https')
http (guessing 'http$1')
url (guessing 'url')
In the browser the app crashes with this console message:
Uncaught ReferenceError: https is not defined
at main.js:8:2
I've tried to setup the rollup-plugin-polyfill-node
referenced in the log but this doesn't fix the issue
I'm also a newbie with Svelte/rollup etc so a simple explanation of what I am doing wrong would be appreciated!
Colyseus.js (the client library) can not be run in a server environment, therefore you want to dynamically import Colyseus.js and run the setup code only after the component/page has mounted, and only in the browser environment.
Assuming this is a SvelteKit app, the following script (in a page or component) should work:
<script>
import { onMount } from 'svelte';
import { browser } from '$app/env';
async function connect() {
let Colyseus = await import("colyseus.js");
let client = new Colyseus.Client('ws://localhost:2567'); // or whereever your colyseus server instance is
let room = await client.joinOrCreate("roomname", { /* options */ });
// good to go
}
onMount(() => {
if(browser) connect();
})
</script>
The key is to conditionally dynamically import Colyseus. A regular import would also import it on the server.