In this short post I will show how to serve a Svelte application from a .Net Core backend.
There are many ways to set this up, but for the purposes of this article I will be using Bazel as the build system. The main benefit of this is that it enables me to use the same build toolchain for compiling both my Svelte code and my .Net code.
Bazel doesn’t really change how you write code in Svelte or .Net, but there is some additional build configuration to add for Bazel. For more details on this I recommend checking out my articles on building Svelte with Bazel and building .Net Core with Bazel.
I have put my demo on Github in case you want to try it out yourself.
To run the demo, simply run yarn and yarn start. This will start a .Net Core web server that serves an index.html page with a Svelte bundle. Bazel is available from npm, so no need to install it separately anymore.
Since both Svelte compilation and C# compilation is managed by Bazel, changing either a Svelte file or a .Net file will re-trigger compilation automatically. I think this is awesome since you can manage the entire app with a single build toolchain.
The Svelte component is intentionally very simple, just a hello world component as you can see below.
The .Net code is mainly just responsible for serving the index.html page where Svelte is loaded. An extension of this would be to add additional api endpoints for the Svelte application to call via fetch or a similar xhr library.
I have included the .Net controller below for reference.
There are likely multiple ways to serve static html files from .Net. I opted for this approach since it seems to work well.
In this short article I shared a simple example where I am using Bazel to build a Svelte/.Net project. I should point out that the Bazel rules for both .Net and Svelte are experimental, but it’s at least stable enough for some POCs and experimentation.