Svelte 3 Under the hood

Cameron Stitt

May 09 2019

Categories: Open Source Frameworks Tags: Svelte JavaScript

With the recent release of Svelte v3, it seemed a good time to dive under the hood and explain exactly what it is doing. For those that don’t know, Svelte is a js library that takes a very different approach than what I have used before. Let’s see how Svelte describes itself:

Svelte is a radical new approach to building user interfaces. Whereas traditional frameworks like React and Vue do the bulk of their work in the browser, Svelte shifts that work into a compile step that happens when you build your app.

We are going to look at a simple compoment, and break down the code that is generated by Svelte.

Our first component

Svelte components are different to other frameworks, in that it combines the HTML, CSS and JS all in one file. Here is a simple hello world example:

Our component
<script>
  let name = 'world';
</script>

<h1>Hello {name}!</h1>

Despite its simplicity, we are going to break down exactly what it is.

let name = 'world';

All we are doing here is declaring a variable name with a default value of world. Behind the scenes however, this becomes a value that can be used throughout the Svelte component.

<h1>Hello {name}!</h1>

Here, we have a standard h1 tag that is saying a friendly hello to the world. With this, we now have a component that will automatically update the dom whenever name changes.

To use this component, we would then simply make a new instance of it and supply it with some options.

Component initialization
new SimpleComponent({
  target: '.simple',
});

The target defines the location in the html to mount the component. There are many more options, but we will keep it simple for now.

Under the hood

Now that we have a component, let’s dive into what Svelte is doing with this component once compiled. It’s important to note that we may not dive into all of Svelte’s internal functions, instead focusing on the core components that make up our output.

Svelte output
/* App.svelte generated by Svelte v3.2.2 */
import {
	SvelteComponent,
	append,
	detach,
	element,
	init,
	insert,
	noop,
	safe_not_equal,
	text
} from "svelte/internal";

function create_fragment(ctx) {
	var h1, t0, t1, t2;

	return {
		c() {
			h1 = element("h1");
			t0 = text("Hello ");
			t1 = text(name);
			t2 = text("!");
		},

		m(target, anchor) {
			insert(target, h1, anchor);
			append(h1, t0);
			append(h1, t1);
			append(h1, t2);
		},

		p: noop,
		i: noop,
		o: noop,

		d(detaching) {
			if (detaching) {
				detach(h1);
			}
		}
	};
}

let name = 'world';

class App extends SvelteComponent {
	constructor(options) {
		super();
		init(this, options, null, create_fragment, safe_not_equal, []);
	}
}

export default App;

Although this file may seem daunting, we will do our best to point out the genius simplicity of the output. Let’s focus on the imports first.

Generated imports
import {
	SvelteComponent,
	append,
	detach,
	element,
	init,
	insert,
	noop,
	safe_not_equal,
	text
} from "svelte/internal";

One of the genius elements of Svelte is the use of it’s internal package. This allows for performant bundles through the use of tree-shaking and code-splitting. These imports provide wide ranging functionality, from creating HTML elements (element) to doing… nothing (noop).

Let’s jump down the end of the file, before we work through the more complex areas.

Generated class
let name = 'world';

class App extends SvelteComponent {
	constructor(options) {
		super();
		init(this, options, null, create_fragment, safe_not_equal, []);
	}
}

Wait, that’s interesting. Our simple name variable declaration has been almost copied over to the output. This is another wonderful advantage to the Svelte 3 design. The use of standard JS syntax means our compiled code can try it’s hardest to re-use as much as possible. The rest of this section is defining a simple class, using the filename as the class name. It extends from SvelteComponent to get all of the required functionality, then implements a simple constructor to initialize the component.

The options argument of the constructor consists of the same arguments we passed in earlier.

{
  target: '.simple'
}

With a more advanced component, this would contain the component’s properties and many other options. The init function call is doing all of the heavy lifting here. It will create our fragment, mount the component onto the page and a lot more.

The create_fragment function is the last generated piece of code for our simple component. Let’s take another look at it.

Generated create_fragment
function create_fragment(ctx) {
	var h1, t0, t1, t2;

	return {
		c() {
			h1 = element("h1");
			t0 = text("Hello ");
			t1 = text(name);
			t2 = text("!");
		},

		m(target, anchor) {
			insert(target, h1, anchor);
			append(h1, t0);
			append(h1, t1);
			append(h1, t2);
		},

		p: noop,
		i: noop,
		o: noop,

		d(detaching) {
			if (detaching) {
				detach(h1);
			}
		}
	};
}

Confusing, right? The purpose of this function is supply a bunch of helpers for managing our component. Let’s take a look at the first one and break down it’s purpose.

Generated constructor
c() {
  h1 = element("h1");
  t0 = text("Hello ");
  t1 = text(name);
  t2 = text("!");
}

Much easier to break down. We can see the content of our component being built up here. A h1 tag, and our hello message. This function c, is shorthand for create.

Onto the next one:

Generated mount call
m(target, anchor) {
  insert(target, h1, anchor);
  append(h1, t0);
  append(h1, t1);
  append(h1, t2);
}

In this case, m is shorthand for mount. It’s simply inserting top level elements and building their node tree as expected.

We will skip p, i, and o for this tutorial, due to them being unused. This means there is only one more piece of the code to look at!

Generated destroy call
d(detaching) {
  if (detaching) {
    detach(h1);
  }
}

Again when looked at in isolation is quite self-explanatory. d is for destroy, and is called when the component is being destroyed. It simply checks if it’s detaching, and calls detach. Simple!

That’s it! Obviously, the more complex the component the more complex the generated code. Hopefully this gives some insight into the underlying beauty of Svelte. If you want to read more, here are some helpful links to get you started: