File this under “it took me a whole 10 minutes to figure out so I thought I’d save you 9 of those”.
Svelte is a front-end framework with a number of advantages, not least of which is that it compiles down to vanilla JS on the server-side and so is quite zippy for the user. One problem that I had getting started with it, though, is that the Svelte docs mostly assume you’re using Node1 on the back-end. But what if you’re a Python person and want to use Flask?
It turns out not to be so bad:
- Put your Svelte files in a directory in the root of your Flask project.
- Set
src/main.js
to target something other than the<body>
— for example:
import App from './App.svelte';
const app = new App({
target: document.querySelector('#svelte-app')
});
- Over in your Flask
routes.py
file, add a catch-all route like the following:2
# Serve Svelte apps
@app.route("/<path:path>")
def svelte_client(path):
return send_from_directory('../svelte/public/', path)
- Finally, add your app target (e.g.
<div id='svelte-app'>
to whatever Jinja template is appropriate, along with<link>
and<script
> tags pointing to your Svelte files:
<link rel='stylesheet' href='/build/bundle.css'>
<script defer src='/build/bundle.js'></script>
And you’re done! Now you can server Svelte from a Flask back-end.