xterm sveltekit integration

241 Views Asked by At

I am trying to output a logfile in the clients browser window. The logfile is on the server.

I found homebridge which I think is doing what I would like to have as well.

I have tried to follow the guide here https://www.npmjs.com/package/xterm but could not get it running:

any idea? thx

+page.svelte

<script>
    import { Terminal } from 'xterm'

    let term = new Terminal()
    term.open(document.getElementById('terminal'))
    term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
</script>

<main>
    <head>
        <link rel="stylesheet" href="node_modules/xterm/css/xterm.css" />
        <script src="node_modules/xterm/lib/xterm.js"></script>
    </head>
    <body>
        <div id="terminal" />
    </body>
</main>

-->

TypeError: Cannot read properties of undefined (reading 'Terminal')     
    at +page.svelte:4:16
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1892:22)
    at Object.default (root.svelte:41:38)
    at Object.default (/src/routes/+layout.svelte:51:34)
    at AppShell.svelte:52:63
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1892:22)
    at eval (/src/routes/+layout.svelte:28:103)
    at Object.$$render (/node_modules/svelte/internal/index.mjs:1892:22)
    at root.svelte:40:37
    at $$render (/node_modules/svelte/internal/index.mjs:1892:22)

1

There are 1 best solutions below

0
awithrow On

xterm is looking for the dom element when it is imported. This hasn't happened yet.

  1. You'll need to import xterm once the page is mounted.

  2. you'll need to bind the terminal element to it.

    <script>
    
     import { onMount } from 'svelte'; //imports the needed onMount handler
     let terminal;                     //creates a var to bind the dom element
    
     onMount(async () => {
       let xterm = await import('xterm'); // import when the dom is ready
       let term = new xterm.Terminal()
       term.open(terminal)                // open the element bound to the var
       term.write('Hello from \x1B[1;3;31mxterm.js\x1B[0m $ ')
     });
    </script>
    
    <link rel="stylesheet" href="node_modules/xterm/css/xterm.css" />
    <div id="terminal" bind:this={terminal}/> <!-- bind the element to the 'terminal' var -->