In this short post I will show how to serve a Svelte application from a .Net Core backend.

Svelte

At the moment Svelte is one of very few good alternatives for building complex web applications with a small JavaScript footprint. Most other frameworks come with a very large payload even for a simple Hello World application. In this post I will show how to serve a Svelte application from .Net.

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

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.

Demo

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.

Svelte

The Svelte component is intentionally very simple, just a hello world component as you can see below.

<h1>{greeting}</h1> <script> let greeting = "Hello from Svelte and .Net"; </script>
.Net

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.

using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace Greetings { [Route ("")] public class HomeController : Controller { [Route ("")] public async Task<IActionResult> Index () { var filePath = Path.Combine (Directory.GetCurrentDirectory (), "src/server.exe/index.html"); using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (var ms = new MemoryStream()) { await stream.CopyToAsync(ms); return File(ms.ToArray(), "text/html"); } } } }

There are likely multiple ways to serve static html files from .Net. I opted for this approach since it seems to work well.

Conclusion

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.