simaec.net Web Publishing

Reactive UI with Svelte

Last updated: 2023-01-12

We use Svelte for our reactive widgets because the platform allows us to isolate and minimize the script necessary for the function of the widget. Further, starting to build apps with Svelte is accessible and without steep learning curve. Here we describe basic setup, develop and deployment with some notes about customizations.

Setup Dev Environment

We recommend following the instructions on the official Svelte Website (see reference below). The documentation is well done and easy to follow.

Once Svelte packages have been installed, we use a simple starter application to setup folders and initial scripts. Make sure that all packages used are the most recent versions.

package.json

Applications which interact with Firestore NoSQL database require additional libraries. See under dependencies:


"dependencies": {
    "firebase": "^9.6.9",
    "sirv-cli": "^2.0.2"
}

rollup.config.js

Under export default we rename the output filename to guarantee that different app don't use the same name.


file: 'public/build/appspecificscriptname.js'

App Initialization

We use class name as app hook and attribute data to pass parameters to the app. We use try catch to prevent javascript error in case the hook doesn't exit in the page html.

Hook HTML


<head>
    ...
    <script defer src='/path/to/script/appspecificname.js'></script>
</head>
<body>
    ...
    <div class="appspecificname" data="optionaldata"></div>
</body>

main.js


import App from './App.svelte';

try {
    var targets = document.querySelectorAll(".appspecificname");
    for (var i = 0; i < targets.length; i++) {
        var target = targets[i];
        var data = target.getAttribute('data');
        if (data && data !== '') {
            var app = new App({
                target: targets[i],
                props: { data: data }
            });
        } else { var app = null}
    }
} catch (error) {
var app = null;
}

export default app;

Notes

Start Local Web Server for Dev and Debug

If npm run dev without assigning port runs into issues on a computer we assign port by force.


PORT=54321 npm run dev

Local Dev

References