repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/vue_rendering_lists/index.md | ---
title: Rendering a list of Vue components
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
At this point we've got a fully working component; we're now ready to add multiple `ToDoItem` components to our app. In this article we'll look at adding a set of todo item data to our `App.vue` component, which we'll then loop through and display inside `ToDoItem` components using the `v-for` directive.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn how to loop through an array of data and render it in multiple
components.
</td>
</tr>
</tbody>
</table>
## Rendering lists with v-for
To be an effective to-do list, we need to be able to render multiple to-do items. To do that, Vue has a special directive, [`v-for`](https://vuejs.org/api/built-in-directives.html#v-for). This is a built-in Vue directive that lets us include a loop inside of our template, repeating the rendering of a template feature for each item in an array. We'll use this to iterate through an array of to-do items and display them in our app in separate `ToDoItem` components.
### Adding some data to render
First we need to get an array of to-do items. To do that, we'll add a `data` property to the `App.vue` component object, containing a `ToDoItems` field whose value is an array of todo items. While we'll eventually add a mechanism to add new todo items, we can start with some mock to do items. Each to-do item will be represented by an object with a `label` and a `done` property.
Add a few sample to-do items, along the lines of those seen below. This way you have some data available for rendering using `v-for`.
```js
export default {
name: "app",
components: {
ToDoItem,
},
data() {
return {
ToDoItems: [
{ label: "Learn Vue", done: false },
{ label: "Create a Vue project with the CLI", done: true },
{ label: "Have fun", done: true },
{ label: "Create a to-do list", done: false },
],
};
},
};
```
Now that we have a list of items, we can use the `v-for` directive to display them. Directives are applied to elements like other attributes. In case of `v-for`, you use a special syntax similar to a [`for...in`](/en-US/docs/Web/JavaScript/Reference/Statements/for...in) loop in JavaScript β `v-for="item in items"` β where `items` is the array you want to iterate over, and `item` is a reference to the current element in the array.
`v-for` attaches to the element you want to repeat, and renders that element and its children. In this case, we want to display an `<li>` element for every to-do item inside our `ToDoItems` array. Then we want to pass the data from each to-do item to a `ToDoItem` component.
### Key attribute
Before we do that, there's one other piece of syntax to know about that is used with `v-for`, the `key` attribute. To help Vue optimize rendering the elements in the list, it tries to patch list elements so it's not recreating them every time the list changes. However, Vue needs help. To make sure it is re-using list elements appropriately, it needs a unique "key" on the same element that you attach `v-for` to.
To make sure that Vue can accurately compare the `key` attributes, they need to be string or numeric values. While it would be great to use the name field, this field will eventually be controlled by user input, which means we can't guarantee that the names would be unique. We could use `lodash.uniqueid()`, however, like we did in the previous article.
1. Import `lodash.uniqueid` into your `App` component in the same way you did with your `ToDoItem` component, using
```js
import uniqueId from "lodash.uniqueid";
```
2. Next, add an `id` field to each element in your `ToDoItems` array, and assign each of them a value of `uniqueId('todo-')`.
The `<script>` element in `App.vue` should now have the following contents:
```js
import ToDoItem from "./components/ToDoItem.vue";
import uniqueId from "lodash.uniqueid";
export default {
name: "app",
components: {
ToDoItem,
},
data() {
return {
ToDoItems: [
{ id: uniqueId("todo-"), label: "Learn Vue", done: false },
{
id: uniqueId("todo-"),
label: "Create a Vue project with the CLI",
done: true,
},
{ id: uniqueId("todo-"), label: "Have fun", done: true },
{ id: uniqueId("todo-"), label: "Create a to-do list", done: false },
],
};
},
};
```
3. Now, add the `v-for` directive and `key` attribute to the `<li>` element in your `App.vue` template, like so:
```html
<ul>
<li v-for="item in ToDoItems" :key="item.id">
<to-do-item label="My ToDo Item" :done="true"></to-do-item>
</li>
</ul>
```
When you make this change, every JavaScript expression between the `<li>` tags will have access to the `item` value in addition to the other component attributes. This means we can pass the fields of our item objects to our `ToDoItem` component β just remember to use the `v-bind` syntax. This is really useful, as we want our todo items to display their `label` properties as their label, not a static label of "My Todo Item". In addition, we want their checked status to reflect their `done` properties, not always be set to `done="true"`.
4. Update the `label="My ToDo Item"` attribute to `:label="item.label"`, and the `:done="true"` attribute to `:done="item.done"`, as seen in context below:
```html
<ul>
<li v-for="item in ToDoItems" :key="item.id">
<to-do-item :label="item.label" :done="item.done"></to-do-item>
</li>
</ul>
```
Now when you look at your running app, it'll show the todo items with their proper names, and if you inspect the source code you'll see that the inputs all have unique `id`s, taken from the object in the `App` component.

## Chance for a slight refactor
There's one little bit of refactoring we can do here. Instead of generating the `id` for the checkboxes inside your `ToDoItem` component, we can turn the `id` into a prop. While this isn't strictly necessary, it makes it easier for us to manage since we already need to create a unique `id` for each todo item anyway.
1. Add a new prop to your `ToDoItem` component β `id`.
2. Make it required, and make its type a `String`.
3. To prevent name collisions, remove the `id` field from your `data` attribute.
4. You are no longer using `uniqueId`, so you need to remove the `import uniqueId from 'lodash.uniqueid';` line, otherwise your app will throw an error.
The `<script>` contents in your `ToDoItem` component should now look something like this:
```js
export default {
props: {
label: { required: true, type: String },
done: { default: false, type: Boolean },
id: { required: true, type: String },
},
data() {
return {
isDone: this.done,
};
},
};
```
Now, over in your `App.vue` component, pass `item.id` as a prop to the `ToDoItem` component. Your `App.vue` template should now look like this:
```html
<template>
<div id="app">
<h1>My To-Do List</h1>
<ul>
<li v-for="item in ToDoItems" :key="item.id">
<to-do-item
:label="item.label"
:done="item.done"
:id="item.id"></to-do-item>
</li>
</ul>
</div>
</template>
```
When you look at your rendered site, it should look the same, but our refactor now means that our `id` is being taken from the data inside `App.vue` and passed into `ToDoItem` as a prop, just like everything else, so things are now more logical and consistent.
## Summary
And that brings us to the end of another article. We now have sample data in place, and a loop that takes each bit of data and renders it inside a `ToDoItem` in our app.
What we really need next is the ability to allow our users to enter their own todo items into the app, and for that we'll need a text `<input>`, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. We'll get to these in the next article.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/svelte_variables_props/index.md | ---
title: "Dynamic behavior in Svelte: working with variables and props"
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Now that we have our markup and styles ready, we can start developing the required features for our Svelte to-do list app. In this article we'll be using variables and props to make our app dynamic, allowing us to add and delete to-dos, mark them as complete, and filter them by status.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
You'll need a terminal with node and npm installed to compile and build
your app.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
Learn and put into practice some basic Svelte concepts, like creating
components, passing data using props, rendering JavaScript expressions into
our markup, modifying the components' state, and iterating over lists.
</td>
</tr>
</tbody>
</table>
## Code along with us
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/03-adding-dynamic-behavior
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/03-adding-dynamic-behavior
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To code along with us using the REPL, start at
<https://svelte.dev/repl/c862d964d48d473ca63ab91709a0a5a0?version=3.23.2>
## Working with to-dos
Our `Todos.svelte` component is currently just displaying static markup; let's start making it a bit more dynamic. We'll take the tasks information from the markup and store it in a `todos` array. We'll also create two variables to keep track of the total number of tasks and the completed tasks.
The state of our component will be represented by these three top-level variables.
1. Create a `<script>` section at the top of `src/components/Todos.svelte` and give it some content, as follows:
```svelte
<script>
let todos = [
{ id: 1, name: "Create a Svelte starter app", completed: true },
{ id: 2, name: "Create your first component", completed: true },
{ id: 3, name: "Complete the rest of the tutorial", completed: false }
];
let totalTodos = todos.length;
let completedTodos = todos.filter((todo) => todo.completed).length;
</script>
```
Now let's do something with that information.
2. Let's start by showing a status message. Find the `<h2>` heading with an `id` of `list-heading` and replace the hardcoded number of active and completed tasks with dynamic expressions:
```svelte
<h2 id="list-heading">{completedTodos} out of {totalTodos} items completed</h2>
```
3. Go to the app, and you should see the "2 out of 3 items completed" message as before, but this time the information is coming from the `todos` array.
4. To prove it, go to that array, and try changing some of the to-do object's completed property values, and even add a new to-do object. Observe how the numbers in the message are updated appropriately.
## Dynamically generating the to-dos from the data
At the moment, our displayed to-do items are all static. We want to iterate over each item in our `todos` array and render the markup for each task, so let's do that now.
HTML doesn't have a way of expressing logic β like conditionals and loops. Svelte does. In this case we use the [`{#each}`](https://svelte.dev/docs/logic-blocks#each) directive to iterate over the `todos` array. The second parameter, if provided, will contain the index of the current item. Also, a key expression can be provided, which will uniquely identify each item. Svelte will use it to diff the list when data changes, rather than adding or removing items at the end, and it's a good practice to always specify one. Finally, an `:else` block can be provided, which will be rendered when the list is empty.
Let's give it a try.
1. Replace the existing `<ul>` element with the following simplified version to get an idea of how it works:
```svelte
<ul>
{#each todos as todo, index (todo.id)}
<li>
<input type="checkbox" checked={todo.completed}/> {index}. {todo.name} (id: {todo.id})
</li>
{:else}
Nothing to do here!
{/each}
</ul>
```
2. Go back to the app; you'll see something like this:

3. Now that we've seen that this is working, let's generate a complete to-do item with each loop of the `{#each}` directive, and inside embed the information from the `todos` array: `id`, `name`, and `completed`. Replace your existing `<ul>` block with the following:
```svelte
<!-- To-dos -->
<ul role="list" class="todo-list stack-large" aria-labelledby="list-heading">
{#each todos as todo (todo.id)}
<li class="todo">
<div class="stack-small">
<div class="c-cb">
<input
type="checkbox"
id="todo-{todo.id}"
checked={todo.completed} />
<label for="todo-{todo.id}" class="todo-label"> {todo.name} </label>
</div>
<div class="btn-group">
<button type="button" class="btn">
Edit <span class="visually-hidden">{todo.name}</span>
</button>
<button type="button" class="btn btn__danger">
Delete <span class="visually-hidden">{todo.name}</span>
</button>
</div>
</div>
</li>
{:else}
<li>Nothing to do here!</li>
{/each}
</ul>
```
Notice how we are using curly braces to embed JavaScript expressions in HTML attributes, like we did with the `checked` and `id` attributes of the checkbox.
We've turned our static markup into a dynamic template ready to display the tasks from our component's state. Great! We are getting there.
## Working with props
With a hardcoded list of to-dos, our `Todos` component is not very useful. To turn our component into a general purpose to-do editor, we should allow the parent of this component to pass in the list of to-dos to edit. This would allow us to save them to a web service or local storage and later retrieve them for update. So let's turn the array into a `prop`.
1. In `Todos.svelte`, replace the existing `let todos = β¦` block with `export let todos = []`.
```js
export let todos = [];
```
This may feel a little weird at first. That's not how `export` normally works in JavaScript modules! This is how Svelte 'extends' JavaScript by taking valid syntax and giving it a new purpose. In this case Svelte is using the `export` keyword to mark a variable declaration as a property or prop, which means it becomes accessible to consumers of the component.
You can also specify a default initial value for a prop. This will be used if the component's consumer doesn't specify the prop on the component β or if its initial value is undefined β when instantiating the component.
So with `export let todos = []`, we are telling Svelte that our `Todos.svelte` component will accept a `todos` attribute, which when omitted will be initialized to an empty array.
2. Have a look at the app, and you'll see the "Nothing to do here!" message. This is because we are currently not passing any value into it from `App.svelte`, so it's using the default value.
3. Now let's move our to-dos to `App.svelte` and pass them to the `Todos.svelte` component as a prop. Update `src/App.svelte` as follows:
```svelte
<script>
import Todos from "./components/Todos.svelte";
let todos = [
{ id: 1, name: "Create a Svelte starter app", completed: true },
{ id: 2, name: "Create your first component", completed: true },
{ id: 3, name: "Complete the rest of the tutorial", completed: false }
];
</script>
<Todos todos={todos} />
```
4. When the attribute and the variable have the same name, Svelte allows you to just specify the variable as a handy shortcut, so we can rewrite our last line like this. Try this now.
```svelte
<Todos {todos} />
```
At this point your to-dos should render just like they did before, except that now we're passing them in from the `App.svelte` component.
## Toggling and removing to-dos
Let's add some functionality to toggle the task status. Svelte has the `on:eventname` directive for listening to DOM events. Let's add a handler to the `on:click` event of the checkbox input to toggle the completed value.
1. Update the `<input type="checkbox">` element inside `src/components/Todos.svelte` as follows:
```svelte
<input type="checkbox" id="todo-{todo.id}"
on:click={() => todo.completed = !todo.completed}
checked={todo.completed}
/>
```
2. Next we'll add a function to remove a to-do from our `todos` array. At the bottom of the `<script>` section of `Todos.svelte`, add the `removeTodo()` function like so:
```js
function removeTodo(todo) {
todos = todos.filter((t) => t.id !== todo.id);
}
```
3. We'll call it via the _Delete_ button. Update it with a `click` event, like so:
```svelte
<button type="button" class="btn btn__danger"
on:click={() => removeTodo(todo)}
>
Delete <span class="visually-hidden">{todo.name}</span>
</button>
```
A very common mistake with handlers in Svelte is to pass the result of executing a function as a handler, instead of passing the function. For example, if you specify `on:click={removeTodo(todo)}`, it will execute `removeTodo(todo)` and the result will be passed as a handler, which is not what we had in mind.
In this case you have to specify `on:click={() => removeTodo(todo)}` as the handler. If `removeTodo()` received no params, you could use `on:event={removeTodo}`, but not `on:event={removeTodo()}`. This is not some special Svelte syntax β here we are just using regular JavaScript [arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions).
Again, this is good progress β at this point, we can now delete tasks. When a to-do item's _Delete_ button is pressed, the relevant to-do is removed from the `todos` array, and the UI updates to no longer show it. In addition, we can now check the checkboxes, and the completed status of the relevant to-dos will now update in the `todos` array.
However, the "x out of y items completed" heading is not being updated. Read on to find out why this is happening and how we can solve it.
## Reactive to-dos
As we've already seen, every time the value of a component top-level variable is modified, Svelte knows how to update the UI. In our app, the `todos` array value is updated directly every time a to-do is toggled or deleted, and so Svelte will update the DOM automatically.
The same is not true for `totalTodos` and `completedTodos`, however. In the following code they are assigned a value when the component is instantiated and the script is executed, but after that, their values are not modified:
```js
let totalTodos = todos.length;
let completedTodos = todos.filter((todo) => todo.completed).length;
```
We could recalculate them after toggling and removing to-dos, but there's an easier way to do it.
We can tell Svelte that we want our `totalTodos` and `completedTodos` variables to be reactive by prefixing them with `$:`. Svelte will generate the code to automatically update them whenever data they depend on is changed.
> **Note:** Svelte uses the `$:` [JavaScript label statement syntax](/en-US/docs/Web/JavaScript/Reference/Statements/label) to mark reactive statements. Just like the `export` keyword being used to declare props, this may look a little alien. This is another example in which Svelte takes advantage of valid JavaScript syntax and gives it a new purpose β in this case to mean "re-run this code whenever any of the referenced values change". Once you get used to it, there's no going back.
Update your `totalTodos` and `completedTodos` variable definitions inside `src/components/Todos.svelte` to look like so:
```js
$: totalTodos = todos.length;
$: completedTodos = todos.filter((todo) => todo.completed).length;
```
If you check your app now, you'll see that the heading's numbers are updated when to-dos are completed or deleted. Nice!
Behind the scenes the Svelte compiler will parse and analyze our code to make a dependency tree, and then it will generate the JavaScript code to re-evaluate each reactive statement whenever one of their dependencies is updated. Reactivity in Svelte is implemented in a very lightweight and performant way, without using listeners, setters, getters, or any other complex mechanism.
## Adding new to-dos
Now on to the next major task for this article β let's add some functionality for adding new to-dos.
1. First we'll create a variable to hold the text of the new to-do. Add this declaration to the `<script>` section of `Todos.svelte` file:
```js
let newTodoName = "";
```
2. Now we will use this value in the `<input>` for adding new tasks. To do that we need to bind our `newTodoName` variable to the `todo-0` input, so that the `newTodoName` variable value stays in sync with the input's `value` property. We could do something like this:
```svelte
<input value={newTodoName} on:keydown={(e) => newTodoName = e.target.value} />
```
Whenever the value of the variable `newTodoName` changes, it will be reflected in the `value` attribute of the input, and whenever a key is pressed in the input, we will update the contents of the variable `newTodoName`.
This is a manual implementation of two-way data binding for an input box. But we don't need to do this β Svelte provides an easier way to bind any property to a variable, using the [`bind:property`](https://svelte.dev/docs/element-directives#bind-property) directive:
```svelte
<input bind:value={newTodoName} />
```
So, let's implement this. Update the `todo-0` input like so:
```svelte
<input
bind:value={newTodoName}
type="text"
id="todo-0"
autocomplete="off"
class="input input__lg" />
```
3. An easy way to test that this works is to add a reactive statement to log the contents of `newTodoName`. Add this snippet at the end of the `<script>` section:
```js
$: console.log("newTodoName: ", newTodoName);
```
> **Note:** As you may have noticed, reactive statements aren't limited to variable declarations. You can put _any_ JavaScript statement after the `$:` sign.
4. Now try going back to `localhost:5042`, pressing <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>K</kbd> to open your browser console and typing something into the input field. You should see your entries logged. At this point, you can delete the reactive `console.log()` if you wish.
5. Next up we'll create a function to add the new to-do β `addTodo()` β which will push a new `todo` object onto the `todos` array. Add this to the bottom of your `<script>` block inside `src/components/Todos.svelte`:
```js
function addTodo() {
todos.push({ id: 999, name: newTodoName, completed: false });
newTodoName = "";
}
```
> **Note:** For the moment we are just assigning the same `id` to every to-do, but don't worry, we will fix that soon.
6. Now we want to update our HTML so that we call `addTodo()` whenever the form is submitted. Update the NewTodo form's opening tag like so:
```svelte
<form on:submit|preventDefault={addTodo}>
```
The [`on:eventname`](https://svelte.dev/docs/element-directives#on-eventname) directive supports adding modifiers to the DOM event with the `|` character. In this case, the `preventDefault` modifier tells Svelte to generate the code to call `event.preventDefault()` before running the handler. Explore the previous link to see what other modifiers are available.
7. If you try adding new to-dos at this point, the new to-dos are added to the to-dos array, but our UI is not updated. Remember that in Svelte [reactivity is triggered with assignments](https://svelte.dev/docs/svelte-components#script-2-assignments-are-reactive). That means that the `addTodo()` function is executed, the element is added to the `todos` array, but Svelte won't detect that the push method modified the array, so it won't refresh the tasks `<ul>`.
Just adding `todos = todos` to the end of the `addTodo()` function would solve the problem, but it seems strange to have to include that at the end of the function. Instead, we'll take out the `push()` method and use [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) to achieve the same result: we'll assign a value to the `todos` array equal to the `todos` array plus the new object.
> **Note:** `Array` has several mutable operations: [`push()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push), [`pop()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop), [`splice()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice), [`shift()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift), [`unshift()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift), [`reverse()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse), and [`sort()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). Using them often causes side effects and bugs that are hard to track. By using the spread syntax instead of `push()` we avoid mutating the array, which is considered a good practice.
Update your `addTodo()` function like so:
```js
function addTodo() {
todos = [...todos, { id: 999, name: newTodoName, completed: false }];
newTodoName = "";
}
```
## Giving each to-do a unique ID
If you try to add new to-dos in your app now, you'll be able to add a new to-do and have it appear in the UI β once. If you try it a second time, it won't work, and you'll get a console message saying "Error: Cannot have duplicate keys in a keyed each". We need unique IDs for our to-dos.
1. Let's declare a `newTodoId` variable calculated from the number of to-dos plus 1, and make it reactive. Add the following snippet to the `<script>` section:
```js
let newTodoId;
$: {
if (totalTodos === 0) {
newTodoId = 1;
} else {
newTodoId = Math.max(...todos.map((t) => t.id)) + 1;
}
}
```
> **Note:** As you can see, reactive statements are not limited to one-liners. The following would work too, but it is a little less readable: `$: newTodoId = totalTodos ? Math.max(...todos.map((t) => t.id)) + 1 : 1`
2. How does Svelte achieve this? The compiler parses the whole reactive statement, and detects that it depends on the `totalTodos` variable and the `todos` array. So whenever either of them is modified, this code is re-evaluated, updating `newTodoId` accordingly.
Let's use this in our `addTodo()` function. Update it like so:
```js
function addTodo() {
todos = [...todos, { id: newTodoId, name: newTodoName, completed: false }];
newTodoName = "";
}
```
## Filtering to-dos by status
Finally for this article, let's implement the ability to filter our to-dos by status. We'll create a variable to hold the current filter, and a helper function that will return the filtered to-dos.
1. At the bottom of our `<script>` section add the following:
```js
let filter = "all";
const filterTodos = (filter, todos) =>
filter === "active"
? todos.filter((t) => !t.completed)
: filter === "completed"
? todos.filter((t) => t.completed)
: todos;
```
We use the `filter` variable to control the active filter: _all_, _active_, or _completed_. Just assigning one of these values to the filter variable will activate the filter and update the list of to-dos. Let's see how to achieve this.
The `filterTodos()` function will receive the current filter and the list of to-dos, and return a new array of to-dos filtered accordingly.
2. Let's update the filter button markup to make it dynamic and update the current filter when the user presses one of the filter buttons. Update it like this:
```svelte
<div class="filters btn-group stack-exception">
<button class="btn toggle-btn" class:btn__primary={filter === 'all'} aria-pressed={filter === 'all'} on:click={() => filter = 'all'} >
<span class="visually-hidden">Show</span>
<span>All</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" class:btn__primary={filter === 'active'} aria-pressed={filter === 'active'} on:click={() => filter = 'active'} >
<span class="visually-hidden">Show</span>
<span>Active</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" class:btn__primary={filter === 'completed'} aria-pressed={filter === 'completed'} on:click={() => filter = 'completed'} >
<span class="visually-hidden">Show</span>
<span>Completed</span>
<span class="visually-hidden">tasks</span>
</button>
</div>
```
There are a couple of things going on in this markup.
We will show the current filter by applying the `btn__primary` class to the active filter button. To conditionally apply style classes to an element we use the `class:name={value}` directive. If the value expression evaluates to truthy, the class name will be applied. You can add many of these directives, with different conditions, to the same element. So when we issue `class:btn__primary={filter === 'all'}`, Svelte will apply the `btn__primary` class if filter equals all.
> **Note:** Svelte provides a shortcut which allows us to shorten `<div class:active={active}>` to `<div class:active>` when the class matches the variable name.
Something similar happens with `aria-pressed={filter === 'all'}`: when the JavaScript expression passed between curly braces evaluates to a truthy value, the `aria-pressed` attribute will be added to the button.
Whenever we click on a button, we update the filter variable by issuing `on:click={() => filter = 'all'}`. Read on to find out how Svelte reactivity will take care of the rest.
3. Now we just need to use the helper function in the `{#each}` loop; update it like this:
```svelte
β¦
<ul role="list" class="todo-list stack-large" aria-labelledby="list-heading">
{#each filterTodos(filter, todos) as todo (todo.id)}
β¦
```
After analyzing our code, Svelte detects that our `filterTodos()` function depends on the variables `filter` and `todos`. And, just like with any other dynamic expression embedded in the markup, whenever any of these dependencies changes, the DOM will be updated accordingly. So whenever `filter` or `todos` changes, the `filterTodos()` function will be re-evaluated and the items inside the loop will be updated.
> **Note:** Reactivity can be tricky sometimes. Svelte recognizes `filter` as a dependency because we are referencing it in the `filterTodos(filter, todo)` expression. `filter` is a top-level variable, so we might be tempted to remove it from the helper function params, and just call it like this: `filterTodos(todo)`. This would work, but now Svelte has no way to find out that `{#each filterTodos(todos) }` depends on `filter`, and the list of filtered to-dos won't be updated when the filter changes. Always remember that Svelte analyzes our code to find out dependencies, so it's better to be explicit about it and not rely on the visibility of top-level variables. Besides, it's a good practice to make our code clear and explicit about what information it is using.
## The code so far
### Git
To see the state of the code as it should be at the end of this article, access your copy of our repo like this:
```bash
cd mdn-svelte-tutorial/04-componentizing-our-app
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/04-componentizing-our-app
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To see the current state of the code in a REPL, visit:
<https://svelte.dev/repl/99b9eb228b404a2f8c8959b22c0a40d3?version=3.23.2>
## Summary
That will do for now! In this article we already implemented most of our desired functionality. Our app can display, add, and delete to-dos, toggle their completed status, show how many of them are completed, and apply filters.
To recap, we covered the following topics:
- Creating and using components
- Turning static markup into a live template
- Embedding JavaScript expressions in our markup
- Iterating over lists using the `{#each}` directive
- Passing information between components with props
- Listening to DOM events
- Declaring reactive statements
- Basic debugging with `console.log()` and reactive statements
- Binding HTML properties with the `bind:property` directive
- Triggering reactivity with assignments
- Using reactive expressions to filter data
- Explicitly defining our reactive dependencies
In the next article we will add further functionality, which will allow users to edit to-dos.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/main_features/index.md | ---
title: Framework main features
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Each major JavaScript framework has a different approach to updating the DOM, handling browser events, and providing an enjoyable developer experience. This article will explore the main features of "the big 4" frameworks, looking at how frameworks tend to work from a high level, and the differences between them.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To understand the main code features of frameworks.</td>
</tr>
</tbody>
</table>
## Domain-specific languages
All of the frameworks discussed in this module are powered by JavaScript, and all allow you to use domain-specific languages (DSLs) in order to build your applications. In particular, React has popularized the use of **JSX** for writing its components, while Ember utilizes **Handlebars**. Unlike HTML, these languages know how to read data variables, and this data can be used to streamline the process of writing your UI.
Angular apps often make heavy use of **TypeScript**. TypeScript is not concerned with the writing of user interfaces, but it is a domain-specific language, and has significant differences to vanilla JavaScript.
DSLs can't be read by the browser directly; they must be transformed into JavaScript or HTML first. [Transformation is an extra step in the development process](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Overview#transformation), but framework tooling generally includes the required tools to handle this step, or can be adjusted to include this step. While it is possible to build framework apps without using these domain-specific languages, embracing them will streamline your development process and make it easier to find help from the communities around those frameworks.
### JSX
[JSX](https://react.dev/learn/writing-markup-with-jsx), which stands for JavaScript and XML, is an extension of JavaScript that brings HTML-like syntax to a JavaScript environment. It was invented by the React team for use in React applications, but can be used to develop other applications β like Vue apps, for instance.
The following shows a simple JSX example:
```jsx
const subject = "World";
const header = (
<header>
<h1>Hello, {subject}!</h1>
</header>
);
```
This expression represents an HTML [`<header>`](/en-US/docs/Web/HTML/Element/header) element with an [`<h1>`](/en-US/docs/Web/HTML/Element/Heading_Elements) element inside. The curly braces around `{subject}` tell the application to read the value of the `subject` constant and insert it into our `<h1>`.
When used with React, the JSX from the previous snippet would be compiled into this:
```js
const subject = "World";
const header = React.createElement(
"header",
null,
React.createElement("h1", null, "Hello, ", subject, "!"),
);
```
When ultimately rendered by the browser, the above snippet will produce HTML that looks like this:
```html
<header>
<h1>Hello, World!</h1>
</header>
```
### Handlebars
The [Handlebars](https://handlebarsjs.com/) templating language is not specific to Ember applications, but it is heavily utilized in Ember apps. Handlebars code resembles HTML, but it has the option of pulling data in from elsewhere. This data can be used to influence the HTML that an application ultimately builds.
Like JSX, Handlebars uses curly braces to inject the value of a variable. Handlebars uses a double-pair of curly braces, instead of a single pair.
Given this Handlebars template:
```html
<header>
<h1>Hello, \{{subject}}!</h1>
</header>
```
And this data:
```js
{
subject: "World";
}
```
Handlebars will build HTML like this:
```html
<header>
<h1>Hello, World!</h1>
</header>
```
### TypeScript
[TypeScript](https://www.typescriptlang.org/) is a _superset_ of JavaScript, meaning it extends JavaScript β all JavaScript code is valid TypeScript, but not the other way around. TypeScript is useful for the strictness it allows developers to enforce on their code. For instance, consider a function `add()`, which takes integers `a` and `b` and returns their sum.
In JavaScript, that function could be written like this:
```js
function add(a, b) {
return a + b;
}
```
This code might be trivial for someone accustomed to JavaScript, but it could still be clearer. JavaScript lets us use the `+` operator to concatenate strings together, so this function would technically still work if `a` and `b` were strings β it just might not give you the result you'd expect. What if we wanted to only allow numbers to be passed into this function? TypeScript makes that possible:
```ts
function add(a: number, b: number) {
return a + b;
}
```
The `: number` written after each parameter here tells TypeScript that both `a` and `b` must be numbers. If we were to use this function and pass `'2'` into it as an argument, TypeScript would raise an error during compilation, and we would be forced to fix our mistake. We could write our own JavaScript that raises these errors for us, but it would make our source code significantly more verbose. It probably makes more sense to let TypeScript handle such checks for us.
## Writing components
As mentioned in the previous chapter, most frameworks have some kind of component model. React components can be written with JSX, Ember components with Handlebars, and Angular and Vue components with a templating syntax that lightly extends HTML.
Regardless of their opinions on how components should be written, each framework's components offer a way to describe the external properties they may need, the internal state that the component should manage, and the events a user can trigger on the component's markup.
The code snippets in the rest of this section will use React as an example, and are written with JSX.
### Properties
Properties, or **props**, are external data that a component needs in order to render. Suppose you're building a website for an online magazine, and you need to be sure that each contributing writer gets credit for their work. You might create an `AuthorCredit` component to go with each article. This component needs to display a portrait of the author and a short byline about them. In order to know what image to render, and what byline to print, `AuthorCredit` needs to accept some props.
A React representation of this `AuthorCredit` component might look something like this:
```jsx
function AuthorCredit(props) {
return (
<figure>
<img src={props.src} alt={props.alt} />
<figcaption>{props.byline}</figcaption>
</figure>
);
}
```
`{props.src}`, `{props.alt}`, and `{props.byline}` represent where our props will be inserted into the component. To render this component, we would write code like this in the place where we want it rendered (which will probably be inside another component):
```jsx
<AuthorCredit
src="./assets/zelda.png"
alt="Portrait of Zelda Schiff"
byline="Zelda Schiff is editor-in-chief of the Library Times."
/>
```
This will ultimately render the following [`<figure>`](/en-US/docs/Web/HTML/Element/figure) element in the browser, with its structure as defined in the `AuthorCredit` component, and its content as defined in the props included on the `AuthorCredit` component call:
```html
<figure>
<img src="assets/zelda.png" alt="Portrait of Zelda Schiff" />
<figcaption>Zelda Schiff is editor-in-chief of the Library Times.</figcaption>
</figure>
```
### State
We talked about the concept of **state** in the previous chapter β a robust state-handling mechanism is key to an effective framework, and each component may have data that needs its state controlled. This state will persist in some way as long as the component is in use. Like props, state can be used to affect how a component is rendered.
As an example, consider a button that counts how many times it has been clicked. This component should be responsible for tracking its own _count_ state, and could be written like this:
```jsx
function CounterButton() {
const [count] = useState(0);
return <button>Clicked {count} times</button>;
}
```
[`useState()`](https://react.dev/reference/react/useState) is a **[React hook](https://react.dev/reference/react)** which, given an initial data value, will keep track of that value as it is updated. The code will be initially rendered like so in the browser:
```html
<button>Clicked 0 times</button>
```
The `useState()` call keeps track of the `count` value in a robust way across the app, without you needing to write code to do that yourself.
### Events
In order to be interactive, components need ways to respond to browser events, so our applications can respond to our users. Frameworks each provide their own syntax for listening to browser events, which reference the names of the equivalent native browser events.
In React, listening for the [`click`](/en-US/docs/Web/API/Element/click_event) event requires a special property, `onClick`. Let's update our `CounterButton` code from above to allow it to count clicks:
```jsx
function CounterButton() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
);
}
```
In this version we are using additional `useState()` functionality to create a special `setCount()` function, which we can invoke to update the value of `count`. We call this function inside the `onClick` event handler to set `count` to whatever its current value is, plus one.
## Styling components
Each framework offers a way to define styles for your components β or for the application as a whole. Although each framework's approach to defining the styles of a component is slightly different, all of them give you multiple ways to do so. With the addition of some helper modules, you can style your framework apps in [Sass](https://sass-lang.com/) or [Less](https://lesscss.org/), or transpile your CSS stylesheets with [PostCSS](https://postcss.org/).
## Handling dependencies
All major frameworks provide mechanisms for handling dependencies β using components inside other components, sometimes with multiple hierarchy levels. As with other features, the exact mechanism will differ between frameworks, but the end result is the same. Components tend to import components into other components using the standard [JavaScript module syntax](/en-US/docs/Web/JavaScript/Guide/Modules), or at least something similar.
### Components in components
One key benefit of component-based UI architecture is that components can be composed together. Just like you can write HTML tags inside each other to build a website, you can use components inside other components to build a web application. Each framework allows you to write components that utilize (and thus depend on) other components.
For example, our `AuthorCredit` React component might be utilized inside an `Article` component. That means that `Article` would need to import `AuthorCredit`.
```js
import AuthorCredit from "./components/AuthorCredit";
```
Once that's done, `AuthorCredit` could be used inside the `Article` component like this:
```jsx
<Article>
<AuthorCredit />
</Article>
```
### Dependency injection
Real-world applications can often involve component structures with multiple levels of nesting. An `AuthorCredit` component nested many levels deep might, for some reason, need data from the very root level of our application.
Let's say that the magazine site we're building is structured like this:
```jsx
<App>
<Home>
<Article>
<AuthorCredit {/* props */} />
</Article>
</Home>
</App>
```
Our `App` component has data that our `AuthorCredit` component needs. We could rewrite `Home` and `Article` so that they know to pass props down, but this could get tedious if there are many, many levels between the origin and destination of our data. It's also excessive: `Home` and `Article` don't actually make use of the author's portrait or byline, but if we want to get that information into the `AuthorCredit`, we will need to change `Home` and `Article` to accommodate it.
The problem of passing data through many layers of components is called prop drilling, and it's not ideal for large applications.
To circumvent prop drilling, frameworks provide functionality known as dependency injection, which is a way to get certain data directly to the components that need it, without passing it through intervening levels. Each framework implements dependency injection under a different name, and in a different way, but the effect is ultimately the same.
Angular calls this process [dependency injection](https://angular.io/guide/dependency-injection); Vue has [`provide()` and `inject()` component methods](https://v2.vuejs.org/v2/api/#provide-inject); React has a [Context API](https://react.dev/learn/passing-data-deeply-with-context); Ember shares state through [services](https://guides.emberjs.com/release/services/).
### Lifecycle
In the context of a framework, a component's **lifecycle** is a collection of phases a component goes through from the time it is appended to the DOM and then rendered by the browser (often called _mounting_) to the time that it is removed from the DOM (often called _unmounting_). Each framework names these lifecycle phases differently, and not all give developers access to the same phases. All of the frameworks follow the same general model: they allow developers to perform certain actions when the component _mounts_, when it _renders_, when it _unmounts_, and at many phases in between these.
The _render_ phase is the most crucial to understand, because it is repeated the most times as your user interacts with your application. It's run every time the browser needs to render something new, whether that new information is an addition to what's in the browser, a deletion, or an edit of what's there.
This [diagram of a React component's lifecycle](https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/) offers a general overview of the concept.
## Rendering elements
Just as with lifecycles, frameworks take different-but-similar approaches to how they render your applications. All of them track the current rendered version of your browser's DOM, and each makes slightly different decisions about how the DOM should change as components in your application re-render. Because frameworks make these decisions for you, you typically don't interact with the DOM yourself. This abstraction away from the DOM is more complex and more memory-intensive than updating the DOM yourself, but without it, frameworks could not allow you to program in the declarative way they're known for.
The **Virtual DOM** is an approach whereby information about your browser's DOM is stored in JavaScript memory. Your application updates this copy of the DOM, then compares it to the "real" DOM β the DOM that is actually rendered for your users β in order to decide what to render. The application builds a "diff" to compare the differences between the updated virtual DOM and the currently rendered DOM, and uses that diff to apply updates to the real DOM. Both React and Vue utilize a virtual DOM model, but they do not apply the exact same logic when diffing or rendering.
You can [read more about the Virtual DOM in the React docs](https://reactjs.org/docs/faq-internals.html#what-is-the-virtual-dom).
The **Incremental DOM** is similar to the virtual DOM in that it builds a DOM diff to decide what to render, but different in that it doesn't create a complete copy of the DOM in JavaScript memory. It ignores the parts of the DOM that do not need to be changed. Angular is the only framework discussed so far in this module that uses an incremental DOM.
You can [read more about the Incremental DOM on the Auth0 blog](https://auth0.com/blog/incremental-dom/).
The **Glimmer VM** is unique to Ember. It is not a virtual DOM nor an incremental DOM; it is a separate process through which Ember's templates are transpiled into a kind of "byte code" that is easier and faster to read than JavaScript.
## Routing
As [mentioned in the previous chapter, routing](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction#routing) is an important part of the web experience. To avoid a broken experience in sufficiently complex apps with lots of views, each of the frameworks covered in this module provides a library (or more than one library) that helps developers implement client-side routing in their applications.
## Testing
All applications benefit from test coverage that ensures your software continues to behave in the way that you'd expect, and web applications are no different. Each framework's ecosystem provides tooling that facilitates the writing of tests. Testing tools are not built into the frameworks themselves, but the command-line interface tools used to generate framework apps give you access to the appropriate testing tools.
Each framework has extensive tools in its ecosystem, with capabilities for unit and integration testing alike.
[Testing Library](https://testing-library.com/) is a suite of testing utilities that has tools for many JavaScript environments, including React, Vue, and Angular. The Ember docs cover the [testing of Ember apps](https://guides.emberjs.com/release/testing/).
Here's a quick test for our `CounterButton` written with the help of React Testing Library β it tests a number of things, such as the button's existence, and whether the button is displaying the correct text after being clicked 0, 1, and 2 times:
```jsx
import { fireEvent, render, screen } from "@testing-library/react";
import CounterButton from "./CounterButton";
it("Renders a semantic button with an initial state of 0", () => {
render(<CounterButton />);
const btn = screen.getByRole("button");
expect(btn).toBeInTheDocument();
expect(btn).toHaveTextContent("Clicked 0 times");
});
it("Increments the count when clicked", () => {
render(<CounterButton />);
const btn = screen.getByRole("button");
fireEvent.click(btn);
expect(btn).toHaveTextContent("Clicked 1 times");
fireEvent.click(btn);
expect(btn).toHaveTextContent("Clicked 2 times");
});
```
## Summary
At this point you should have more of an idea about the actual languages, features, and tools you'll be using as you create applications with frameworks. I'm sure you're enthusiastic to get going and actually do some coding, and that's what you are going to do next! At this point you can choose which framework you'd like to start learning first:
- [React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started)
- [Ember](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started)
- [Vue](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started)
- [Svelte](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started)
- [Angular](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_getting_started)
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/angular_building/index.md | ---
title: Building Angular applications and further resources
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_building
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenu("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_filtering", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
This final Angular article covers how to build an app ready for production, and provides further resources for you to continue your learning journey.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn how to build your Angular app.</td>
</tr>
</tbody>
</table>
## Building your finished application
Now that you are finished developing your application, you can run the Angular CLI `build` command.
When you run the `build` command in your `todo` directory, your application compiles into an output directory named `dist/`.
In the `todo` directory, run the following command at the command line:
```bash
ng build -c production
```
The CLI compiles the application and puts the output in a new `dist` directory.
The `--configuration production`/`-c production` flag with `ng build` gets rid of stuff you don't need for production.
## Deploying your application
To deploy your application, you can copy the contents of the `dist/my-project-name` folder to your web server.
Because these files are static, you can host them on any web server capable of serving files, such as:
- Node.js
- Java
- .NET
You can use any backend such as [Firebase](https://firebase.google.com/docs/hosting), [Google Cloud](https://cloud.google.com/solutions/web-hosting), or [App Engine](https://cloud.google.com/appengine/docs/standard/python/getting-started/hosting-a-static-website).
## What's next
At this point, you've built a basic application, but your Angular journey is just beginning.
You can learn more by exploring the Angular documentation, such as:
- [Tour of Heroes](https://angular.io/tutorial): An in-depth tutorial highlighting Angular features, such as using services, navigation, and getting data from a server.
- The Angular [Components](https://angular.io/guide/component-overview) guides: A series of articles that cover topics such as lifecycle, component interaction, and view encapsulation.
- The [Forms](https://angular.io/guide/forms-overview) guides: Articles that guide you through building reactive forms in Angular, validating input, and building dynamic forms.
## Summary
That's it for now. We hope you had fun with Angular!
{{PreviousMenu("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_filtering", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/ember_structure_componentization/index.md | ---
title: Ember app structure and componentization
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
In this article we'll get right on with planning out the structure of our TodoMVC Ember app, adding in the HTML for it, and then breaking that HTML structure into components.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
A deeper understanding of modern JavaScript features (such as classes,
modules, etc.), will be extremely beneficial, as Ember makes heavy use
of them.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn how to structure an Ember app, and then break that structure
into components.
</td>
</tr>
</tbody>
</table>
## Planning out the layout of the TodoMVC app
In the last article we set up a new Ember project, then added and configured our CSS styles. At this point we add some HTML, planning out the structure and semantics of our TodoMVC app.
The landing page HTML of our application is defined in `app/templates/application.hbs`. This already exists, and its contents currently look like so:
```hbs
\{{!-- The following component displays Ember's default welcome message. --}}
<WelcomePage />
\{{!-- Feel free to remove this! --}}
\{{outlet}}
```
`<WelcomePage />` is a component provided by an Ember addon that renders the default welcome page we saw in the previous article, when we first navigated to our server at `localhost:4200`.
However, we don't want this. Instead, we want it to contain the TodoMVC app structure. To start with, delete the contents of `application.hbs` and replace them with the following:
```html
<section class="todoapp">
<h1>todos</h1>
<input
class="new-todo"
aria-label="What needs to be done?"
placeholder="What needs to be done?"
autofocus />
</section>
```
> **Note:** [`aria-label`](/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-label) provides a label for assistive technology to make use of β for example, for a screen reader to read out. This is useful in such cases where we have an [`<input>`](/en-US/docs/Web/HTML/Element/input) being used with no corresponding HTML text that could be turned into a label.
When you save `application.hbs`, the development server you started earlier will automatically rebuild the app and refresh the browser. The rendered output should now look like this:

It doesn't take too much effort to get our HTML looking like a fully-featured to-do list app. Update the `application.hbs` file again so its content looks like this:
```html
<section class="todoapp">
<h1>todos</h1>
<input
class="new-todo"
aria-label="What needs to be done?"
placeholder="What needs to be done?"
autofocus />
<section class="main">
<input id="mark-all-complete" class="toggle-all" type="checkbox" />
<label for="mark-all-complete">Mark all as complete</label>
<ul class="todo-list">
<li>
<div class="view">
<input
aria-label="Toggle the completion of this todo"
class="toggle"
type="checkbox" />
<label>Buy Movie Tickets</label>
<button
type="button"
class="destroy"
title="Remove this todo"></button>
</div>
<input autofocus class="edit" value="Todo Text" />
</li>
<li>
<div class="view">
<input
aria-label="Toggle the completion of this todo"
class="toggle"
type="checkbox" />
<label>Go to Movie</label>
<button
type="button"
class="destroy"
title="Remove this todo"></button>
</div>
<input autofocus class="edit" value="Todo Text" />
</li>
</ul>
</section>
<footer class="footer">
<span class="todo-count"> <strong>0</strong> todos left </span>
<ul class="filters">
<li>
<a href="#">All</a>
<a href="#">Active</a>
<a href="#">Completed</a>
</li>
</ul>
<button type="button" class="clear-completed">Clear Completed</button>
</footer>
</section>
```
The rendered output should now be as follows:

This looks pretty complete, but remember that this is only a static prototype. Now we need to break up our HTML code into dynamic components; later we'll turn it into a fully interactive app.
Looking at the code next to the rendered todo app, there are a number of ways we could decide how to break up the UI, but let's plan on splitting the HTML out into the following components:

The component groupings are as follows:
- The main input / "new-todo" (red in the image)
- The containing body of the todo list + the `mark-all-complete` button (purple in the image)
- The `mark-all-complete button`, explicitly highlighted for reasons given below (yellow in the image)
- Each todo is an individual component (green in the image)
- The footer (blue in the image)
Something odd to note is that the `mark-all-complete` checkbox (marked in yellow), while in the "main" section, is rendered next to the "new-todo" input. This is because the default CSS absolutely positions the checkbox + label with negative top and left values to move it next to the input, rather than it being inside the "main" section.

## Using the CLI to create our components for us
So to represent our app, we want to create 4 components:
- Header
- List
- Individual Todo
- Footer
To create a component, we use the `ember generate component` command, followed by the name of the component. Let's create the header component first. To do so:
1. Stop the server running by going to the terminal and pressing <kbd>Ctrl</kbd> + <kbd>C</kbd>.
2. Enter the following command into your terminal:
```bash
ember generate component header
```
These will generate some new files, as shown in the resulting terminal output:
```plain
installing component
create app/components/header.hbs
skip app/components/header.js
tip to add a class, run `ember generate component-class header`
installing component-test
create tests/integration/components/header-test.js
```
`header.hbs` is the template file where we'll include the HTML structure for just that component. Later on we'll add the required dynamic functionality such as data bindings, responding to user interaction, etc.
> **Note:** The `header.js` file (shown as skipped) is for connection to a backing Glimmer Component Class, which we don't need for now, as they are for adding interactivity and state manipulation. By default, `generate component` generates template-only components, because in large applications, template-only components end up being the majority of the components.
`header-test.js` is for writing automated tests to ensure that our app continues to work over time as we upgrade, add features, refactor, etc. Testing is outside the scope of this tutorial, although generally testing should be implemented as you develop, rather than after, otherwise it tends to be forgotten about. If you're curious about testing, or why you would want to have automated tests, check out the [official Ember tutorial on testing](https://guides.emberjs.com/release/tutorial/part-1/automated-testing/).
Before we start adding any component code, let's create the scaffolding for the other components. Enter the following lines into your terminal, one by one:
```bash
ember generate component todo-list
ember generate component todo
ember generate component footer
```
You'll now see the following inside your `todomvc/app/components` directory:

Now that we have all of our component structure files, we can cut and paste the HTML for each component out of the `application.hbs` file and into each of those components, and then re-write the `application.hbs` to reflect our new abstractions.
1. The `header.hbs` file should be updated to contain the following:
```html
<input
class="new-todo"
aria-label="What needs to be done?"
placeholder="What needs to be done?"
autofocus />
```
2. `todo-list.hbs` should be updated to contain this chunk of code:
```html
<section class="main">
<input id="mark-all-complete" class="toggle-all" type="checkbox" />
<label for="mark-all-complete">Mark all as complete</label>
<ul class="todo-list">
<Todo />
<Todo />
</ul>
</section>
```
> **Note:** The only non-HTML in this new `todo-list.hbs` is the `<Todo />` component invocation. In Ember, a component invocation is similar to declaring an HTML element, but the first letter starts with a capital letter, and the names are written in {{Glossary("camel_case", "upper camel case")}}, as you'll see with `<TodoList />` later on. The contents of the `todo.hbs` file below will replace `<Todo />` in the rendered page as our application loads.
3. Add the following into the `todo.hbs` file:
```html
<li>
<div class="view">
<input
aria-label="Toggle the completion of this todo"
class="toggle"
type="checkbox" />
<label>Buy Movie Tickets</label>
<button type="button" class="destroy" title="Remove this todo"></button>
</div>
<input autofocus class="edit" value="Todo Text" />
</li>
```
4. `footer.hbs` should be updated to contain the following:
```html
<footer class="footer">
<span class="todo-count"> <strong>0</strong> todos left </span>
<ul class="filters">
<li>
<a href="#">All</a>
<a href="#">Active</a>
<a href="#">Completed</a>
</li>
</ul>
<button type="button" class="clear-completed">Clear Completed</button>
</footer>
```
5. Finally, the contents of `application.hbs` should be updated so that they call the appropriate components, like so:
```hbs
<section class="todoapp">
<h1>todos</h1>
<Header />
<TodoList />
<Footer />
</section>
```
6. With these changes made, run `npm start` in your terminal again, then head over to `http://localhost:4200` to ensure that the todo app still looks as it did before the refactor.

Notice how the todo items both say "Buy Movie Tickets" β this is because the same component is being invoked twice, and the todo text is hardcoded into it. We'll look at showing different todo items in the next article!
## Summary
Great! Everything looks as it should. We have successfully refactored our HTML into components! In the next article we'll start looking into adding interactivity to our Ember application.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/vue_resources/index.md | ---
title: Vue resources
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Now we'll round off our study of Vue by giving you a list of resources that you can use to go further in your learning, plus some other useful tips.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn where to go to find further information on Vue, to continue
your learning.
</td>
</tr>
</tbody>
</table>
## Further resources
Here's where you should go to learn more about Vue:
- [Vue Docs](https://vuejs.org/) β The main Vue site. Contains comprehensive documentation, including examples, cookbooks, and reference material. This is the best place to start learning Vue in depth.
- [Vue GitHub Repo](https://github.com/vuejs/vue) β The Vue code itself. This is where you can report issues and/or contribute directly to the Vue codebase. Studying the Vue source code can help you better understand how the framework works, and write better code.
- [Vue Forum](https://forum.vuejs.org/) β The official forum for getting help with Vue.
- [Vue CLI Docs](https://cli.vuejs.org/) β Documentation for the Vue CLI. This contains information on customizing and extending the output you are generating via the CLI.
- [Nuxt](https://nuxt.com/) β Nuxt is a Server-Side Vue Framework, with some architectural opinions that can be useful to creating maintainable applications, even if you don't use any of the Server Side Rendering features it provides. This site provides detailed documentation on using Nuxt.
- [Vue Mastery](https://www.vuemastery.com/courses/) β A paid education platform that specializes in Vue, including some free lessons.
- [Vue School](https://vueschool.io/) β Another paid education platform specializing in Vue.
## Building and publishing your Vue app
The Vue CLI also provides us with tools for preparing our app for publishing to the web. You can do this like so:
- If your local server is still running, end it by pressing <kbd>Ctrl</kbd> \+ <kbd>C</kbd> in the terminal.
- Next, run the `npm run build` (or `yarn build`) in the console.
This will create a new `dist` directory containing all of your production ready files. To publish your site to the web, copy the contents of this folder to your hosting environment.
> **Note:** The Vue CLI docs also include a [specific guide on how to publish your app](https://cli.vuejs.org/guide/deployment.html#platform-guides) to many of the common hosting platforms.
## Vue 2
Vue 2 support will end on December 31st, 2023 and the default Vue version for all CLI tools will be version 3 and above.
The [Composition API](https://vuejs.org/guide/extras/composition-api-faq.html) works as an alternative to the property-based API where a `setup()` function is used on the component. Only what you return from this function is available in your `<template>`s. You are required to be explicit about "reactive" properties when using this API. Vue handles this for you using the [Options API](https://vuejs.org/guide/extras/composition-api-faq.html#trade-offs). This makes the new API typically considered a more advanced use case.
If you're upgrading from Vue 2, it's recommended you take a look at the [Vue 3 migration guide](https://v3-migration.vuejs.org/).
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/svelte_stores/index.md | ---
title: Working with Svelte stores
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
In the last article we completed the development of our app, finished organizing it into components, and discussed some advanced techniques for dealing with reactivity, working with DOM nodes, and exposing component functionality. In this article we will show another way to handle state management in Svelte: [Stores](https://learn.svelte.dev/tutorial/writable-stores). Stores are global data repositories that hold values. Components can subscribe to stores and receive notifications when their values change.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
You'll need a terminal with node and npm installed to compile and build
your app.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>Learn how to use Svelte stores</td>
</tr>
</tbody>
</table>
Using stores we will create an `Alert` component that shows notifications on screen, which can receive messages from any component. In this case, the `Alert` component is independent of the rest β it is not a parent or child of any other β so the messages don't fit into the component hierarchy.
We will also see how to develop our own custom store to persist the todo information to [web storage](/en-US/docs/Web/API/Web_Storage_API), allowing our to-dos to persist over page reloads.
## Code along with us
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/06-stores
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/06-stores
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To code along with us using the REPL, start at
<https://svelte.dev/repl/d1fa84a5a4494366b179c87395940039?version=3.23.2>
## Dealing with our app state
We have already seen how our components can communicate with each other using props, two-way data binding, and events. In all these cases we were dealing with communication between parent and child components.
But not all application state belongs inside your application's component hierarchy. For example, information about the logged-in user, or whether the dark theme is selected or not.
Sometimes, your app state will need to be accessed by multiple components that are not hierarchically related, or by a regular JavaScript module.
Moreover, when your app becomes complicated and your component hierarchy gets complex, it might become too difficult for components to relay data between each other. In that case, moving to a global data store might be a good option. If you've already worked with [Redux](https://redux.js.org/) or [Vuex](https://vuex.vuejs.org/), then you'll be familiar with how this kind of store works. Svelte stores offer similar features for state management.
A store is an object with a `subscribe()` method that allows interested parties to be notified whenever the store value changes and an optional `set()` method that allows you to set new values for the store. This minimal API is known as the [store contract](https://svelte.dev/docs/svelte-components#script-4-prefix-stores-with-$-to-access-their-values-store-contract).
Svelte provides functions for creating [readable](https://svelte.dev/docs/svelte-store#readable), [writable](https://svelte.dev/docs/svelte-store#writable), and [derived](https://svelte.dev/docs/svelte-store#derived) stores in the `svelte/store` module.
Svelte also provides a very intuitive way to integrate stores into its reactivity system using the [reactive `$store` syntax](https://svelte.dev/docs/svelte-components#script-4-prefix-stores-with-$-to-access-their-values). If you create your own stores honoring the store contract, you get this reactivity syntactic sugar for free.
## Creating the Alert component
To show how to work with stores, we will create an `Alert` component. These kinds of widgets might also be known as popup notifications, toast, or notification bubbles.
Our `Alert` component will be displayed by the `App` component, but any component can send notifications to it. Whenever a notification arrives, the `Alert` component will be in charge of displaying it on screen.
### Creating a store
Let's start by creating a writable store. Any component will be able to write to this store, and the `Alert` component will subscribe to it and display a message whenever the store is modified.
1. Create a new file, `stores.js`, inside your `src` directory.
2. Give it the following content:
```js
import { writable } from "svelte/store";
export const alert = writable("Welcome to the to-do list app!");
```
> **Note:** Stores can be defined and used outside Svelte components, so you can organize them in any way you please.
In the above code we import the `writable()` function from `svelte/store` and use it to create a new store called `alert` with an initial value of "Welcome to the to-do list app!". We then `export` the store.
### Creating the actual component
Let's now create our `Alert` component and see how we can read values from the store.
1. Create another new file named `src/components/Alert.svelte`.
2. Give it the following content:
```svelte
<script>
import { alert } from '../stores.js'
import { onDestroy } from 'svelte'
let alertContent = ''
const unsubscribe = alert.subscribe((value) => alertContent = value)
onDestroy(unsubscribe)
</script>
{#if alertContent}
<div on:click={() => alertContent = ''}>
<p>{ alertContent }</p>
</div>
{/if}
<style>
div {
position: fixed;
cursor: pointer;
margin-right: 1.5rem;
margin-left: 1.5rem;
margin-top: 1rem;
right: 0;
display: flex;
align-items: center;
border-radius: 0.2rem;
background-color: #565656;
color: #fff;
font-weight: 700;
padding: 0.5rem 1.4rem;
font-size: 1.5rem;
z-index: 100;
opacity: 95%;
}
div p {
color: #fff;
}
div svg {
height: 1.6rem;
fill: currentcolor;
width: 1.4rem;
margin-right: 0.5rem;
}
</style>
```
Let's walk through this piece of code in detail.
- At the beginning we import the `alert` store.
- Next we import the `onDestroy()` lifecycle function, which lets us execute a callback after the component has been unmounted.
- We then create a local variable named `alertContent`. Remember that we can access top-level variables from the markup, and whenever they are modified, the DOM will update accordingly.
- Then we call the method `alert.subscribe()`, passing it a callback function as a parameter. Whenever the value of the store changes, the callback function will be called with the new value as its parameter. In the callback function we just assign the value we receive to the local variable, which will trigger the update of the component's DOM.
- The `subscribe()` method also returns a cleanup function, which takes care of releasing the subscription. So we subscribe when the component is being initialized, and use `onDestroy` to unsubscribe when the component is unmounted.
- Finally we use the `alertContent` variable in our markup, and if the user clicks on the alert we clean it.
- At the end we include a few CSS lines to style our `Alert` component.
This setup allows us to work with stores in a reactive way. When the value of the store changes, the callback is executed. There we assign a new value to a local variable, and thanks to Svelte reactivity all our markup and reactive dependencies are updated accordingly.
### Using the component
Let's now use our component.
1. In `App.svelte` we'll import the component. Add the following import statement below the existing one:
```js
import Alert from "./components/Alert.svelte";
```
2. Then call the `Alert` component just above the `Todos` call, like this:
```svelte
<Alert />
<Todos {todos} />
```
3. Load your test app now, and you should now see the `Alert` message on screen. You can click on it to dismiss it.

## Making stores reactive with the reactive `$store` syntax
This works, but you'll have to copy and paste all this code every time you want to subscribe to a store:
```svelte
<script>
import myStore from "./stores.js";
import { onDestroy } from "svelte";
let myStoreContent = "";
const unsubscribe = myStore.subscribe((value) => (myStoreContent = value));
onDestroy(unsubscribe);
</script>
{myStoreContent}
```
That's too much boilerplate for Svelte! Being a compiler, Svelte has more resources to make our lives easier. In this case Svelte provides the reactive `$store` syntax, also known as auto-subscription. In simple terms, you just prefix the store with the `$` sign and Svelte will generate the code to make it reactive automatically. So our previous code block can be replaced with this:
```svelte
<script>
import myStore from "./stores.js";
</script>
{$myStore}
```
And `$myStore` will be fully reactive. This also applies to your own custom stores. If you implement the `subscribe()` and `set()` methods, as we'll do later, the reactive `$store` syntax will also apply to your stores.
1. Let's apply this to our `Alert` component. Update the `<script>` and markup sections of `Alert.svelte` as follows:
```svelte
<script>
import { alert } from '../stores.js'
</script>
{#if $alert}
<div on:click={() => $alert = ''}>
<p>{ $alert }</p>
</div>
{/if}
```
2. Check your app again and you'll see that this works just like before. That's much better!
Behind the scenes Svelte has generated the code to declare the local variable `$alert`, subscribe to the `alert` store, update `$alert` whenever the store's content is modified, and unsubscribe when the component is unmounted. It will also generate the `alert.set()` statements whenever we assign a value to `$alert`.
The end result of this nifty trick is that you can access global stores just as easily as using reactive local variables.
This is a perfect example of how Svelte puts the compiler in charge of better developer ergonomics, not only saving us from typing boilerplate, but also generating less error-prone code.
## Writing to our store
Writing to our store is just a matter of importing it and executing `$store = 'new value'`. Let's use it in our `Todos` component.
1. Add the following `import` statement below the existing ones:
```js
import { alert } from "../stores.js";
```
2. Update your `addTodo()` function like so:
```js
function addTodo(name) {
todos = [...todos, { id: newTodoId, name, completed: false }];
$alert = `Todo '${name}' has been added`;
}
```
3. Update `removeTodo()` like so:
```js
function removeTodo(todo) {
todos = todos.filter((t) => t.id !== todo.id);
todosStatus.focus(); // give focus to status heading
$alert = `Todo '${todo.name}' has been deleted`;
}
```
4. Update the `updateTodo()` function to this:
```js
function updateTodo(todo) {
const i = todos.findIndex((t) => t.id === todo.id);
if (todos[i].name !== todo.name)
$alert = `todo '${todos[i].name}' has been renamed to '${todo.name}'`;
if (todos[i].completed !== todo.completed)
$alert = `todo '${todos[i].name}' marked as ${
todo.completed ? "completed" : "active"
}`;
todos[i] = { ...todos[i], ...todo };
}
```
5. Add the following reactive block beneath the block that starts with `let filter = 'all'`:
```js
$: {
if (filter === "all") {
$alert = "Browsing all to-dos";
} else if (filter === "active") {
$alert = "Browsing active to-dos";
} else if (filter === "completed") {
$alert = "Browsing completed to-dos";
}
}
```
6. And finally for now, update the `const checkAllTodos` and `const removeCompletedTodos` blocks as follows:
```js
const checkAllTodos = (completed) => {
todos = todos.map((t) => ({ ...t, completed }));
$alert = `${completed ? "Checked" : "Unchecked"} ${todos.length} to-dos`;
};
const removeCompletedTodos = () => {
$alert = `Removed ${todos.filter((t) => t.completed).length} to-dos`;
todos = todos.filter((t) => !t.completed);
};
```
7. So basically, we've imported the store and updated it on every event, which causes a new alert to show each time. Have a look at your app again, and try adding/deleting/updating a few to-dos!
As soon as we execute `$alert = β¦`, Svelte will run `alert.set()`. Our `Alert` component β like every subscriber to the alert store β will be notified when it receives a new value, and thanks to Svelte reactivity its markup will be updated.
We could do the same within any component or `.js` file.
> **Note:** Outside Svelte components you cannot use the `$store` syntax. That's because the Svelte compiler won't touch anything outside Svelte components. In that case you'll have to rely on the `store.subscribe()` and `store.set()` methods.
## Improving our Alert component
It's a bit annoying having to click on the alert to get rid of it. It would be better if the notification just disappeared after a couple of seconds.
Let's see how to do that. We'll specify a prop with the milliseconds to wait before clearing the notification, and we'll define a timeout to remove the alert. We'll also take care of clearing the timeout when the `Alert` component is unmounted to prevent memory leaks.
1. Update the `<script>` section of your `Alert.svelte` component like so:
```js
import { onDestroy } from "svelte";
import { alert } from "../stores.js";
export let ms = 3000;
let visible;
let timeout;
const onMessageChange = (message, ms) => {
clearTimeout(timeout);
if (!message) {
// hide Alert if message is empty
visible = false;
} else {
visible = true; // show alert
if (ms > 0) timeout = setTimeout(() => (visible = false), ms); // and hide it after ms milliseconds
}
};
$: onMessageChange($alert, ms); // whenever the alert store or the ms props changes run onMessageChange
onDestroy(() => clearTimeout(timeout)); // make sure we clean-up the timeout
```
2. And update the `Alert.svelte` markup section like so:
```svelte
{#if visible}
<div on:click={() => visible = false}>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M12.432 0c1.34 0 2.01.912 2.01 1.957 0 1.305-1.164 2.512-2.679 2.512-1.269 0-2.009-.75-1.974-1.99C9.789 1.436 10.67 0 12.432 0zM8.309 20c-1.058 0-1.833-.652-1.093-3.524l1.214-5.092c.211-.814.246-1.141 0-1.141-.317 0-1.689.562-2.502 1.117l-.528-.88c2.572-2.186 5.531-3.467 6.801-3.467 1.057 0 1.233 1.273.705 3.23l-1.391 5.352c-.246.945-.141 1.271.106 1.271.317 0 1.357-.392 2.379-1.207l.6.814C12.098 19.02 9.365 20 8.309 20z"/></svg>
<p>{ $alert }</p>
</div>
{/if}
```
Here we first create the prop `ms` with a default value of 3000 (milliseconds). Then we create an `onMessageChange()` function that will take care of controlling whether the Alert is visible or not. With `$: onMessageChange($alert, ms)` we tell Svelte to run this function whenever the `$alert` store or the `ms` prop changes.
Whenever the `$alert` store changes, we'll clean up any pending timeout. If `$alert` is empty, we set `visible` to `false` and the `Alert` will be removed from the DOM. If it is not empty, we set `visible` to `true` and use the `setTimeout()` function to clear the alert after `ms` milliseconds.
Finally, with the `onDestroy()` lifecycle function, we make sure to call the `clearTimeout()` function.
We also added an SVG icon above the alert paragraph, to make it look a bit nicer. Try it out again, and you should see the changes.
## Making our Alert component accessible
Our `Alert` component is working fine, but it's not very friendly to assistive technologies. The problem is elements that are dynamically added and removed from the page. While visually evident to users who can see the page, they may not be so obvious to users of assistive technologies, like screen readers. To handle those situations, we can take advantage of [ARIA live regions](/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions), which provide a way to programmatically expose dynamic content changes so that they can be detected and announced by assistive technologies.
We can declare a region that contains dynamic content that should be announced by assistive technologies with the `aria-live` property followed by the politeness setting, which is used to set the priority with which screen readers should handle updates to that regions. The possible settings are `off`, `polite`, or `assertive`.
For common situations, you also have several predefined specialized `role` values that can be used, like `log`, `status` and `alert`.
In our case, just adding a `role="alert"` to the `<div>` container will do the trick, like this:
```svelte
<div role="alert" on:click={() => visible = false}>
```
In general, testing your applications using screen readers is a good idea, not only to discover accessibility issues but also to get used to how visually impaired people use the Web. You have several options, like [NVDA](https://www.nvaccess.org/) for Windows, [ChromeVox](https://support.google.com/chromebook/answer/7031755) for Chrome, [Orca](https://wiki.gnome.org/Projects/Orca) on Linux, and [VoiceOver](https://www.apple.com/accessibility/vision/) for macOS and iOS, among other options.
To learn more about detecting and fixing accessibility issues, check out our [Handling common accessibility problems](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing/Accessibility) article.
## Using the store contract to persist our to-dos
Our little app lets us manage our to-dos quite easily, but is rather useless if we always get the same list of hardcoded to-dos when we reload it. To make it truly useful, we have to find out how to persist our to-dos.
First we need some way for our `Todos` component to give back the updated to-dos to its parent. We could emit an updated event with the list of to-dos, but it's easier just to bind the `todos` variable. Let's open `App.svelte` and try it.
1. First, add the following line below your `todos` array:
```js
$: console.log("todos", todos);
```
2. Next, update your `Todos` component call as follows:
```svelte
<Todos bind:todos />
```
> **Note:** `<Todos bind:todos />` is just a shortcut for `<Todos bind:todos={todos} />`.
3. Go back to your app, try adding some to-dos, then go to your developer tools web console. You'll see that every modification we make to our to-dos is reflected in the `todos` array defined in `App.svelte` thanks to the `bind` directive.
Now we have to find a way to persist these to-dos. We could implement some code in our `App.svelte` component to read and save our to-dos to [web storage](/en-US/docs/Web/API/Web_Storage_API) or to a web service.
But wouldn't it be better if we could develop some generic store that allows us to persist its content? This would allow us to use it just like any other store, and abstract away the persistence mechanism. We could create a store that syncs its content to web storage, and later develop another one that syncs against a web service. Switching between them would be trivial and we wouldn't have to touch `App.svelte` at all.
### Saving our to-dos
So let's start by using a regular writable store to save our to-dos.
1. Open the file `stores.js` and add the following store below the existing one:
```js
export const todos = writable([]);
```
2. That was easy. Now we need to import the store and use it in `App.svelte`. Just remember that to access the to-dos now we have to use the `$todos` reactive `$store` syntax.
Update your `App.svelte` file like this:
```svelte
<script>
import Todos from "./components/Todos.svelte";
import Alert from "./components/Alert.svelte";
import { todos } from "./stores.js";
$todos = [
{ id: 1, name: "Create a Svelte starter app", completed: true },
{ id: 2, name: "Create your first component", completed: true },
{ id: 3, name: "Complete the rest of the tutorial", completed: false }
];
</script>
<Alert />
<Todos bind:todos={$todos} />
```
3. Try it out; everything should work. Next we'll see how to define our own custom stores.
### How to implement a store contract: The theory
You can create your own stores without relying on `svelte/store` by implementing the store contract. Its features must work like so:
1. A store must contain a `subscribe()` method, which must accept as its argument a subscription function. All of a store's active subscription functions must be called whenever the store's value changes.
2. The `subscribe()` method must return an `unsubscribe()` function, which when called must stop its subscription.
3. A store may optionally contain a `set()` method, which must accept as its argument a new value for the store, and which synchronously calls all of the store's active subscription functions. A store with a `set()` method is called a writable store.
First, let's add the following `console.log()` statements to our `App.svelte` component to see the `todos` store and its content in action. Add these lines below the `todos` array:
```js
console.log("todos store - todos:", todos);
console.log("todos store content - $todos:", $todos);
```
When you run the app now, you'll see something like this in your web console:

As you can see, our store is just an object containing `subscribe()`, `set()`, and `update()` methods, and `$todos` is our array of to-dos.
Just for reference, here's a basic working store implemented from scratch:
```js
export const writable = (initial_value = 0) => {
let value = initial_value; // content of the store
let subs = []; // subscriber's handlers
const subscribe = (handler) => {
subs = [...subs, handler]; // add handler to the array of subscribers
handler(value); // call handler with current value
return () => (subs = subs.filter((sub) => sub !== handler)); // return unsubscribe function
};
const set = (new_value) => {
if (value === new_value) return; // same value, exit
value = new_value; // update value
subs.forEach((sub) => sub(value)); // update subscribers
};
const update = (update_fn) => set(update_fn(value)); // update function
return { subscribe, set, update }; // store contract
};
```
Here we declare `subs`, which is an array of subscribers. In the `subscribe()` method we add the handler to the `subs` array and return a function that, when executed, will remove the handler from the array.
When we call `set()`, we update the value of the store and call each handler, passing the new value as a parameter.
Usually you don't implement stores from scratch; instead you'd use the writable store to create [custom stores](https://learn.svelte.dev/tutorial/custom-stores) with domain-specific logic. In the following example we create a counter store, which will only allow us to add one to the counter or reset its value:
```js
import { writable } from "svelte/store";
function myStore() {
const { subscribe, set, update } = writable(0);
return {
subscribe,
addOne: () => update((n) => n + 1),
reset: () => set(0),
};
}
```
If our to-do list app gets too complex, we could let our to-dos store handle every state modification. We could move all the methods that modify the `todo` array (like `addTodo()`, `removeTodo()`, etc.) from our `Todos` component to the store. If you have a central place where all the state modification is applied, components could just call those methods to modify the app's state and reactively display the info exposed by the store. Having a unique place to handle state modifications makes it easier to reason about the state flow and spot issues.
Svelte won't force you to organize your state management in a specific way; it just provides the tools for you to choose how to handle it.
### Implementing our custom to-dos store
Our to-do list app is not particularly complex, so we won't move all our modification methods into a central place. We'll just leave them as they are, and instead concentrate on persisting our to-dos.
> **Note:** If you are following this guide working from the Svelte REPL, you won't be able to complete this step. For security reasons the Svelte REPL works in a sandboxed environment which will not let you access web storage, and you will get a "The operation is insecure" error. In order to follow this section, you'll have to clone the repo and go to the `mdn-svelte-tutorial/06-stores` folder, or you can directly download the folder's content with `npx degit opensas/mdn-svelte-tutorial/06-stores`.
To implement a custom store that saves its content to web storage, we will need a writable store that does the following:
- Initially reads the value from web storage, and if it's not present, initializes it with a default value
- Whenever the value is modified, updates the store itself and also the data in local storage
Moreover, because web storage only supports saving string values, we will have to convert from object to string when saving, and vice versa when we are loading the value from local storage.
1. Create a new file called `localStore.js`, in your `src` directory.
2. Give it the following content:
```js
import { writable } from "svelte/store";
export const localStore = (key, initial) => {
// receives the key of the local storage and an initial value
const toString = (value) => JSON.stringify(value, null, 2); // helper function
const toObj = JSON.parse; // helper function
if (localStorage.getItem(key) === null) {
// item not present in local storage
localStorage.setItem(key, toString(initial)); // initialize local storage with initial value
}
const saved = toObj(localStorage.getItem(key)); // convert to object
const { subscribe, set, update } = writable(saved); // create the underlying writable store
return {
subscribe,
set: (value) => {
localStorage.setItem(key, toString(value)); // save also to local storage as a string
return set(value);
},
update,
};
};
```
- Our `localStore` will be a function that when executed initially reads its content from web storage, and returns an object with three methods: `subscribe()`, `set()`, and `update()`.
- When we create a new `localStore`, we'll have to specify the key of the web storage and an initial value. We then check if the value exists in web storage and, if not, we create it.
- We use the [`localStorage.getItem(key)`](/en-US/docs/Web/API/Storage/getItem) and [`localStorage.setItem(key, value)`](/en-US/docs/Web/API/Storage/setItem) methods to read and write information to web storage, and the [`toString()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString) and `toObj()` (which uses [`JSON.parse()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)) helper functions to convert the values.
- Next, we convert the string content received from the web storage to an object, and save that object in our store.
- Finally, every time we update the contents of the store, we also update the web storage, with the value converted to a string.
Notice that we only had to redefine the `set()` method, adding the operation to save the value to web storage. The rest of the code is mostly initializing and converting stuff.
3. Now we will use our local store from `stores.js` to create our locally persisted to-dos store.
Update `stores.js` like so:
```js
import { writable } from "svelte/store";
import { localStore } from "./localStore.js";
export const alert = writable("Welcome to the to-do list app!");
const initialTodos = [
{ id: 1, name: "Visit MDN web docs", completed: true },
{ id: 2, name: "Complete the Svelte Tutorial", completed: false },
];
export const todos = localStore("mdn-svelte-todo", initialTodos);
```
Using `localStore('mdn-svelte-todo', initialTodos)`, we are configuring the store to save the data in web storage under the key `mdn-svelte-todo`. We also set a couple of todos as initial values.
4. Now let's get rid of the hardcoded to-dos in `App.svelte`. Update its contents as follows. We are basically just deleting the `$todos` array and the `console.log()` statements:
```svelte
<script>
import Todos from './components/Todos.svelte'
import Alert from './components/Alert.svelte'
import { todos } from './stores.js'
</script>
<Alert />
<Todos bind:todos={$todos} />
```
> **Note:** This is the only change we have to make in order to use our custom store. `App.svelte` is completely transparent in terms of what kind of store we are using.
5. Go ahead and try your app again. Create a few to-dos and then close the browser. You may even stop the Svelte server and restart it. Upon revisiting the URL, your to-dos will still be there.
6. You can also inspect it in the DevTools console. In the web console, enter the command `localStorage.getItem('mdn-svelte-todo')`. Make some changes to your app, like pressing the _Uncheck All_ button, and check the web storage content once more. You will get something like this:

Svelte stores provide a very simple and lightweight, but extremely powerful, way to handle complex app state from a global data store in a reactive way. And because Svelte compiles our code, it can provide the [`$store` auto-subscription syntax](https://svelte.dev/docs/svelte-components#script-4-prefix-stores-with-$-to-access-their-values) that allows us to work with stores in the same way as local variables. Because stores have a minimal API, it's very simple to create our custom stores to abstract away the inner workings of the store itself.
## Bonus track: Transitions
Let's change the subject now and do something fun and different: add an animation to our alerts. Svelte provides a whole module to define [transitions](https://learn.svelte.dev/tutorial/transition) and [animations](https://learn.svelte.dev/tutorial/animate) so we can make our user interfaces more appealing.
A transition is applied with the [transition:fn](https://svelte.dev/docs/element-directives#transition-fn) directive, and is triggered by an element entering or leaving the DOM as a result of a state change. The `svelte/transition` module exports seven functions: `fade`, `blur`, `fly`, `slide`, `scale`, `draw`, and `crossfade`.
Let's give our `Alert` component a fly `transition`. We'll open the `Alert.svelte` file and import the `fly` function from the `svelte/transition` module.
1. Put the following `import` statement below the existing ones:
```js
import { fly } from "svelte/transition";
```
2. To use it, update your opening `<div>` tag like so:
```svelte
<div role="alert" on:click={() => visible = false}
transition:fly
>
```
Transitions can also receive parameters, like this:
```svelte
<div role="alert" on:click={() => visible = false}
transition:fly="\{{delay: 250, duration: 300, x: 0, y: -100, opacity: 0.5}}"
>
```
> **Note:** The double curly braces are not special Svelte syntax. It's just a literal JavaScript object being passed as a parameter to the fly transition.
3. Try your app out again, and you'll see that the notifications now look a bit more appealing.
> **Note:** Being a compiler allows Svelte to optimize the size of our bundle by excluding features that are not used. In this case, if we compile our app for production with `npm run build`, our `public/build/bundle.js` file will weight a little less than 22 KB. If we remove the `transitions:fly` directive Svelte is smart enough to realize the fly function is not being used and the `bundle.js` file size will drop down to just 18 KB.
This is just the tip of the iceberg. Svelte has lots of options for dealing with animations and transitions. Svelte also supports specifying different transitions to apply when the element is added or removed from the DOM with the `in:fn`/`out:fn` directives, and it also allows you to define your [custom CSS](https://learn.svelte.dev/tutorial/custom-css-transitions) and [JavaScript](https://learn.svelte.dev/tutorial/custom-js-transitions) transitions. It also has several easing functions to specify the rate of change over time. Have a look at the [ease visualizer](https://svelte.dev/examples/easing) to explore the various ease functions available.
## The code so far
### Git
To see the state of the code as it should be at the end of this article, access your copy of our repo like this:
```bash
cd mdn-svelte-tutorial/07-next-steps
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/07-next-steps
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To see the current state of the code in a REPL, visit:
<https://svelte.dev/repl/378dd79e0dfe4486a8f10823f3813190?version=3.23.2>
## Summary
In this article we added two new features: an `Alert` component and persisting `todos` to web storage.
- This allowed us to showcase some advanced Svelte techniques. We developed the `Alert` component to show how to implement cross-component state management using stores. We also saw how to auto-subscribe to stores to seamlessly integrate them with the Svelte reactivity system.
- Then we saw how to implement our own store from scratch, and also how to extend Svelte's writable store to persist data to web storage.
- At the end we had a look at using the Svelte `transition` directive to implement animations on DOM elements.
In the next article we will learn how add TypeScript support to our Svelte application. To take advantage of all its features, we will also port our entire application to TypeScript.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/ember_getting_started/index.md | ---
title: Getting started with Ember
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
In our first Ember article we will look at how Ember works and what it's useful for, install the Ember toolchain locally, create a sample app, and then do some initial setup to get it ready for development.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
A deeper understanding of modern JavaScript features (such as classes,
modules, etc.), will be extremely beneficial, as Ember makes heavy use
of them.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn how to install Ember, and create a starter app.</td>
</tr>
</tbody>
</table>
## Introducing Ember
Ember is a component-service framework that focuses on the overall web application development experience, minimizing the trivial differences between applications β all while being a modern and light layer on top of native JavaScript. Ember also has immense backwards and forwards compatibility to help businesses stay up to date with the latest versions of Ember and latest community-driven conventions.
What does it mean to be a component-service framework? Components are individual bundles of behavior, style, and markup β much like what other frontend frameworks provide, such as React, Vue, and Angular. The service side provides long-lived shared state, behavior, and an interface to integrating with other libraries or systems. For example, the Router (which will be mentioned later in this tutorial) is a service. Components and Services make up the majority of any EmberJS application.
## Use cases
Generally, EmberJS works well for building apps that desire either or both of the following traits:
- Single Page Applications, including native-like web apps, and [progressive web apps](/en-US/docs/Web/Progressive_web_apps) (PWAs)
- Ember works best when it is the entire front end of your application.
- Increasing cohesion among many team's technology stacks
- Community-backed "best practices" allow for faster long-term development speed.
- Ember has clear conventions that are useful for enforcing consistency and helping team members get up to speed quickly.
### Ember with add-ons
EmberJS has a plugin architecture, which means that add-ons can be installed and provide additional functionality without much, if any, configuration.
Examples include:
- [PREmber](https://github.com/ef4/prember): Static website rendering for blogs or marketing content.
- [FastBoot](https://ember-fastboot.com/): Server-side rendering, including improving search-engine optimization (SEO), or improving initial render performance of complex, highly interactive web pages.
- [empress-blog](https://empress-blog.netlify.app/welcome/): Authoring blog posts in markdown while optimizing for SEO with PREmber.
- [ember-service-worker](https://ember-service-worker.com/): Configuring a PWA so that the app can be installed on mobile devices, just like apps from the device's respective app-store.
### Native mobile apps
Ember can also be used with native mobile apps with a native-mobile bridge to JavaScript, such as that provided by [Corber](http://corber.io/).
## Opinions
EmberJS is one of the most opinionated front-end frameworks out there. But what does it mean to be opinionated? In Ember, opinions are a set of conventions that help increase the efficiency of developers at the cost of having to learn those conventions. As conventions are defined and shared, the opinions that back those conventions help reduce the menial differences between apps β a common goal among all opinionated frameworks, across any language and ecosystem. Developers are then more easily able to switch between projects and applications without having to completely relearn the architecture, patterns, conventions, etc.
As you work through this series of tutorials, you'll notice Ember's opinions β such as strict naming conventions of component files.
## How does Ember relate to vanilla JavaScript?
Ember is built on JavaScript technologies and is a thin layer on top of traditional [object-oriented programming](/en-US/docs/Learn/JavaScript/Objects/Object-oriented_programming), while still allowing developers to utilize [functional programming techniques](https://opensource.com/article/17/6/functional-javascript).
Ember makes use of two main syntaxes:
- JavaScript (or optionally, [TypeScript](https://www.typescriptlang.org/))
- Ember's own templating language, which is loosely based on [Handlebars](https://handlebarsjs.com/guide/).
The templating language is used to make build and runtime optimizations that otherwise wouldn't be possible. Most importantly, it is a superset of HTML β meaning that anyone who knows HTML can make meaningful contributions to any Ember project with minimal fear of breaking code. Designers and other non-developers can contribute to page templates without any knowledge of JavaScript, and interactivity can be added later.
This language also enables lighter asset payloads due to _compiling_ the templates into a "byte code" that can be parsed faster than JavaScript. The **Glimmer VM** enables extremely fast DOM change tracking without the need to manage and diff a cached virtual representation (which is a common approach to mitigating the slow I/O of DOM changes).
For more information on the technical aspects of The Glimmer VM, the GitHub repository has some [documentation](https://github.com/glimmerjs/glimmer-vm/tree/master/guides) β specifically, [References](https://github.com/glimmerjs/glimmer-vm/blob/master/guides/04-references.md) and [Validators](https://github.com/glimmerjs/glimmer-vm/blob/master/guides/05-validators.md) may be of interest.
Everything else in Ember is _just_ JavaScript. In particular, JavaScript classes. This is where most of the "framework" parts come into play, as there are [superclasses](<https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Subclasses_and_superclasses>), where each type of _thing_ has a different purpose and different expected location within your project.
Here is a demonstration the impact Ember has on the JavaScript that is in typical projects:
[Gavin Demonstrates how < 20% of the JS written is specific to Ember](https://twitter.com/gavinjoyce/status/1174726713101705216).

## Getting started
The rest of the Ember material you'll find here consists of a multi-part tutorial, in which we'll make a version of the classic [TodoMVC sample app](https://todomvc.com/), teaching you how to use the essentials of the Ember framework along the way. TodoMVC is a basic to-do tracking app implemented in many different technologies.
[Here is the completed Ember version](https://nullvoxpopuli.github.io/ember-todomvc-tutorial/), for reference.
### A note on TodoMVC and accessibility
The TodoMVC project has a few issues in terms of adhering to accessible/default web practices. There are a couple of GitHub issues open about this on the TodoMVC family of projects:
- [Add keyboard access to demos](https://github.com/tastejs/todomvc/issues/1017)
- [Re-enable Outline on focusable elements](https://github.com/tastejs/todomvc-app-css/issues/35)
Ember has a strong commitment to being accessible by default and there is an [entire section of the Ember Guides on accessibility](https://guides.emberjs.com/release/accessibility/) on what it means for website / app design.
That said, because this tutorial is a focus on the JavaScript side of making a small web application, TodoMVC's value comes from providing pre-made CSS and recommended HTML structure, which eliminates small differences between implementations, allowing for easier comparison. Later on in the tutorial, we'll focus on adding code to our application to fix some of TodoMVC's biggest faults.
## Installing the Ember tooling
Ember uses a command-line interface (CLI) tool for building and scaffolding parts of your application.
1. You'll need node and npm installed before you can install ember-cli. [Go here to find out how to install node and npm](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line#adding_powerups), if you haven't already got them.
2. Now type the following into your terminal to install ember-cli:
```bash
npm install -g ember-cli
```
This tool provides the `ember` program in your terminal, which is used to create, build, develop, test, and scaffold your application (run `ember --help` for a full list of commands and their options).
3. To create a brand new application, type the following in your terminal. This creates a new directory inside the current directory you are in called todomvc, containing the scaffolding for a new Ember app. Make sure you navigate to somewhere appropriate in the terminal before you run it. (Good suggestions are your "desktop" or "documents" directories, so that it is easy to find):
```bash
ember new todomvc
```
Or, on Windows:
```bash
npx ember-cli new todomvc
```
This generates a production-ready application development environment that includes the following features by default:
- Development server with live reload.
- Plugin-architecture that allows for third-party packages to richly enhance your application.
- The latest JavaScript via Babel and Webpack integration.
- Automated testing environment that runs your tests in the browser, allowing you to _test like a user_.
- Transpilation, and minification, of both CSS and JavaScript for production builds.
- Conventions for minimizing the differences between applications (allowing easier mental context switching).
## Getting ready to build our Ember project
You'll need a code editor before continuing to interact with your brand new project. If you don't have one configured already, [The Ember Atlas](https://www.notion.so/Editors-Tooling-5da96f0b2baf4ce1bf3fd58e3b60c7f6) has some guides on how to set up various editors.
### Installing the shared assets for TodoMVC projects
Installing shared assets, as we're about to do, isn't normally a required step for new projects, but it allows us to use existing shared CSS so we don't need to try to guess at what CSS is needed to create the TodoMVC styles.
1. First, enter into your `todomvc` directory in the terminal, for example using `cd todomvc` in macOS/Linux.
2. Now run the following command to place the common todomvc CSS inside your app:
```bash
npm install --save-dev todomvc-app-css todomvc-common
```
3. Next, find the [ember-cli-build.js](https://github.com/ember-cli/ember-cli/blob/master/blueprints/app/files/ember-cli-build.js) file inside the todomvc directory (it's right there inside the root) and open it in your chosen code editor. ember-cli-build.js is responsible for configuring details about how your project is built β including bundling all your files together, asset minification, and creating sourcemaps β with reasonable defaults, so you don't typically need to worry about this file.
We will however add lines to the ember-cli-build.js file to import our shared CSS files, so that they become part of our build without having to explicitly [`@import`](/en-US/docs/Web/CSS/@import) them into the `app.css` file (this would require URL rewrites at build time and therefore be less efficient and more complicated to set up).
4. In `ember-cli-build.js`, find the following code:
```js
let app = new EmberApp(defaults, {
// Add options here
});
```
5. Add the following lines underneath it before saving the file:
```js
app.import("node_modules/todomvc-common/base.css");
app.import("node_modules/todomvc-app-css/index.css");
```
For more information on what `ember-cli-build.js` does, and for other ways in which you can customize your build / pipeline, the Ember Guides have a page on [Addons and Dependencies](https://guides.emberjs.com/release/addons-and-dependencies/).
6. Finally, find `app.css`, located at `app/styles/app.css`, and paste in the following:
```css
:focus,
.view label:focus,
.todo-list li .toggle:focus + label,
.toggle-all:focus + label {
/* !important needed because todomvc styles deliberately disable the outline */
outline: #d86f95 solid !important;
}
```
This CSS overrides some of the styles provided by the `todomvc-app-css` npm package, therefore allowing keyboard focus to be visible. This goes some way towards fixing one of the major accessibility disadvantages of the default TodoMVC app.
### Starting the development server
You may start the app in _development_ mode by typing the following command in your terminal, while inside the `todomvc` directory:
```bash
ember server
```
This should give you an output similar to the following:
```plain
Build successful (190ms) β Serving on http://localhost:4200/
Slowest Nodes (totalTime >= 5%) | Total (avg)
-----------------------------------------+-----------
BroccoliMergeTrees (17) | 35ms (2 ms)
Package /assets/vendor.js (1) | 13ms
Concat: Vendor Styles/assets/vend... (1) | 12ms
```
The development server launches at `http://localhost:4200`, which you can visit in your browser to check out what your work looks like so far.
If everything is working correctly, you should see a page like this:

> **Note:** on Windows systems without [Windows Subsystem for Linux (WSL)](https://docs.microsoft.com/windows/wsl/install), you will experience slower build-times overall compared to macOS, Linux, and Windows _with_ WSL.
## Summary
So far so good. We've got to the point where we can start build up our sample TodoMVC app in Ember. In the next article we'll look at building up the markup structure of our app, as a group of logical components.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/react_getting_started/index.md | ---
title: Getting started with React
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
In this article we will say hello to React. We'll discover a little bit of detail about its background and use cases, set up a basic React toolchain on our local computer, and create and play with a simple starter app β learning a bit about how React works in the process.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
React uses an HTML-in-JavaScript syntax called JSX (JavaScript and
XML). Familiarity with both HTML and JavaScript will help you to learn
JSX, and better identify whether bugs in your application are related
to JavaScript or to the more specific domain of React.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
<p>
To set up a local React development environment, create a start app, and
understand the basics of how it works.
</p>
</td>
</tr>
</tbody>
</table>
## Hello React
As its official tagline states, [React](https://react.dev/) is a library for building user interfaces. React is not a framework β it's not even exclusive to the web. It's used with other libraries to render to certain environments. For instance, [React Native](https://reactnative.dev/) can be used to build mobile applications.
To build for the web, developers use React in tandem with [ReactDOM](https://react.dev/reference/react-dom). React and ReactDOM are often discussed in the same spaces as β and utilized to solve the same problems as β other true web development frameworks. When we refer to React as a "framework", we're working with that colloquial understanding.
React's primary goal is to minimize the bugs that occur when developers are building UIs. It does this through the use of components β self-contained, logical pieces of code that describe a portion of the user interface. These components can be composed together to create a full UI, and React abstracts away much of the rendering work, leaving you to concentrate on the UI design.
## Use cases
Unlike the other frameworks covered in this module, React does not enforce strict rules around code conventions or file organization. This allows teams to set conventions that work best for them, and to adopt React in any way they would like to. React can handle a single button, a few pieces of an interface, or an app's entire user interface.
While React _can_ be used for [small pieces of an interface](https://react.dev/learn/add-react-to-an-existing-project), it's not as easy to "drop into" an application as a library like jQuery, or even a framework like Vue β it is more approachable when you build your entire app with React.
In addition, many of the developer-experience benefits of a React app, such as writing interfaces with JSX, require a compilation process. Adding a compiler like Babel to a website makes the code on it run slowly, so developers often set up such tooling with a build step. React arguably has a heavy tooling requirement, but it can be learned.
This article is going to focus on the use case of using React to render the entire user interface of an application with the support of [Vite](https://vitejs.dev/), a modern front-end build tool.
## How does React use JavaScript?
React utilizes features of modern JavaScript for many of its patterns. Its biggest departure from JavaScript comes with the use of [JSX](https://react.dev/learn/writing-markup-with-jsx) syntax. JSX extends JavaScript's syntax so that HTML-like code can live alongside it. For example:
```jsx
const heading = <h1>Mozilla Developer Network</h1>;
```
This heading constant is known as a **JSX expression**. React can use it to render that [`<h1>`](/en-US/docs/Web/HTML/Element/Heading_Elements) tag in our app.
Suppose we wanted to wrap our heading in a [`<header>`](/en-US/docs/Web/HTML/Element/header) tag, for semantic reasons? The JSX approach allows us to nest our elements within each other, just like we do with HTML:
```jsx
const header = (
<header>
<h1>Mozilla Developer Network</h1>
</header>
);
```
> **Note:** The parentheses in the previous snippet aren't unique to JSX, and don't have any effect on your application. They're a signal to you (and your computer) that the multiple lines of code inside are part of the same expression. You could just as well write the header expression like this:
>
> ```jsx-nolint
> const header = <header>
> <h1>Mozilla Developer Network</h1>
> </header>;
> ```
>
> However, this looks kind of awkward, because the [`<header>`](/en-US/docs/Web/HTML/Element/header) tag that starts the expression is not indented to the same position as its corresponding closing tag.
Of course, your browser can't read JSX without help. When compiled (using a tool like [Babel](https://babeljs.io/) or [Parcel](https://parceljs.org/)), our header expression would look like this:
```jsx
const header = React.createElement(
"header",
null,
React.createElement("h1", null, "Mozilla Developer Network"),
);
```
It's _possible_ to skip the compilation step and use [`React.createElement()`](https://react.dev/reference/react/createElement) to write your UI yourself. In doing this, however, you lose the declarative benefit of JSX, and your code becomes harder to read. Compilation is an extra step in the development process, but many developers in the React community think that the readability of JSX is worthwhile. Plus, modern front-end development almost always involves a build process anyway β you have to downlevel modern syntax to be compatible with older browsers, and you may want to [minify](/en-US/docs/Glossary/Minification) your code to optimize loading performance. Popular tooling like Babel already comes with JSX support out-of-the-box, so you don't have to configure compilation yourself unless you want to.
Because JSX is a blend of HTML and JavaScript, some developers find it intuitive. Others say that its blended nature makes it confusing. Once you're comfortable with it, however, it will allow you to build user interfaces more quickly and intuitively, and allow others to better understand your codebase at a glance.
To read more about JSX, check out the React team's [Writing Markup with JSX](https://react.dev/learn/writing-markup-with-jsx) article.
## Setting up your first React app
There are many ways to create a new React application. We're going to use Vite to create a new application via the command line.
It's possible to [add React to an existing project](https://react.dev/learn/add-react-to-an-existing-project) by copying some [`<script>`](/en-US/docs/Web/HTML/Element/script) elements into an HTML file, but using Vite will allow you to spend more time building your app and less time fussing with setup.
### Requirements
In order to use Vite, you need to have [Node.js](https://nodejs.org/en/) installed. As of Vite 5.0, at least Node version 18 or later is required, and it's a good idea to run the latest long term support (LTS) version when you can. As of 24th October 2023, Node 20 is the latest LTS version. Node includes npm (the Node package manager).
To check your version of Node, run the following in your terminal:
```bash
node -v
```
If Node is installed, you'll see a version number. If it isn't, you'll see an error message. To install Node, follow the instructions on the [Node.js website](https://nodejs.org/en/).
You may use the Yarn package manager as an alternative to npm but we'll assume you're using npm in this set of tutorials. See [Package management basics](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Package_management) for more information on npm and yarn.
If you're using Windows, you will need to install some software to give you parity with Unix/macOS terminal in order to use the terminal commands mentioned in this tutorial. **Gitbash** (which comes as part of the [git for Windows toolset](https://gitforwindows.org/)) or **[Windows Subsystem for Linux](https://docs.microsoft.com/windows/wsl/about)** (**WSL**) are both suitable. See [Command line crash course](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line) for more information on these, and on terminal commands in general.
Also bear in mind that React and ReactDOM produce apps that only work on a fairly modern set of browsers like Firefox, Microsoft Edge, Safari, or Chrome when working through these tutorials.
See the following for more information:
- ["About npm" on the npm blog](https://docs.npmjs.com/about-npm/)
- ["Introducing npx" on the npm blog](https://blog.npmjs.org/post/162869356040/introducing-npx-an-npm-package-runner)
- [Vite's documentation](https://vitejs.dev/guide/)
### Initializing your app
The npm package manager comes with a `create` command that allows you to create new projects from templates. We can use it to create a new app from Vite's standard React template. Make sure you `cd` to the place you'd like your app to live on your machine, then run the following in your terminal:
```bash
npm create vite@latest moz-todo-react -- --template react
```
This creates a `moz-todo-react` directory using Vite's `react` template.
> **Note:** The `--` is necessary to pass arguments to npm commands such as `create`, and the `--template react` argument tells Vite to use its React template.
Your terminal will have printed some messages if this command was successful. You should see text prompting you to `cd` to your new directory, install the app's dependencies, and run the app locally. Let's start with two of those commands. Run the following in your terminal:
```bash
cd moz-todo-react && npm install
```
Once the process is complete, we need to start a local development server to run our app. Here, we're going to add some command line flags to Vite's default suggestion to open the app in our browser as soon as the server starts, and use port 3000.
Run the following in your terminal:
```bash
npm run dev -- --open --port 3000
```
Once the server starts, you should see a new browser tab containing your React app:

### Application structure
Vite gives us everything we need to develop a React application. Its initial file structure looks like this:
```plain
moz-todo-react
βββ README.md
βββ index.html
βββ node_modules
βββ package-lock.json
βββ package.json
βββ public
β βββ vite.svg
βββ src
β βββ App.css
β βββ App.jsx
β βββ assets
β β βββ react.svg
β βββ index.css
β βββ main.jsx
βββ vite.config.js
```
**`index.html`** is the most important top-level file. Vite injects your code into this file so that your browser can run it. You won't need to edit this file during our tutorial, but you should change the text inside the [`<title>`](/en-US/docs/Web/HTML/Element/title) element in this file to reflect the title of your application. Accurate page titles are important for accessibility.
The **`public`** directory contains static files that will be served directly to your browser without being processed by Vite's build tooling. Right now, it only contains a Vite logo.
The **`src`** directory is where we'll spend most of our time, as it's where the source code for our application lives. You'll notice that some JavaScript files in this directory end in the extension `.jsx`. This extension is necessary for any file that contains JSX β it tells Vite to turn the JSX syntax into JavaScript that your browser can understand. The `src/assets` directory contains the React logo you saw in the browser.
The `package.json` and `package-lock.json` files contain metadata about our project. These files are not unique to React applications: Vite populated `package.json` for us, and npm created `package-lock.json` for when we installed the app's dependencies. You don't need to understand these files at all to complete this tutorial. However, if you'd like to learn more about them, you can read about [`package.json`](https://docs.npmjs.com/cli/v9/configuring-npm/package-json/) and [`package-lock.json`](https://docs.npmjs.com/cli/v9/configuring-npm/package-lock-json) in the npm docs. We also talk about `package.json` in our [Package management basics](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Package_management) tutorial.
### Customizing our dev script
Before we move on, you might want to change your `package.json` file a little bit so that you don't have to pass the `--open` and `--port` flags every time you run `npm run dev`. Open `package.json` in your text editor and find the `scripts` object. Change the `"dev"` key so that it looks like this:
```diff
- "dev": "vite",
+ "dev": "vite --open --port 3000",
```
With this in place, your app will open in your browser at `http://localhost:3000` every time you run `npm run dev`.
> **Note:** You _don't_ need the extra `--` here because we're passing arguments directly to `vite`, rather than to a pre-defined npm script.
## Exploring our first React component β `<App />`
In React, a **component** is a reusable module that renders a part of our overall application. Components can be big or small, but they are usually clearly defined: they serve a single, obvious purpose.
Let's open `src/App.jsx`, since our browser is prompting us to edit it. This file contains our first component, `<App />`:
```jsx
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import "./App.css";
function App() {
const [count, setCount] = useState(0);
return (
<>
<div>
<a href="https://vitejs.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.jsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
);
}
export default App;
```
The `App.jsx` file consists of three main parts: some [`import`](/en-US/docs/Web/JavaScript/Reference/Statements/import) statements at the top, the `App()` function in the middle, and an [`export`](/en-US/docs/Web/JavaScript/Reference/Statements/export) statement at the bottom. Most React components follow this pattern.
### Import statements
The `import` statements at the top of the file allow `App.jsx` to use code that has been defined elsewhere. Let's look at these statements more closely.
```jsx
import { useState } from "react";
import reactLogo from "./assets/react.svg";
import viteLogo from "/vite.svg";
import "./App.css";
```
The first statement imports the `useState` hook from the `react` library. Hooks are a way of using React's features inside a component. We'll talk more about hooks later in this tutorial.
After that, we import `reactLogo` and `viteLogo`. Note that their import paths start with `./` and `/` respectively and that they end with the `.svg` extension at the end. This tells us that these imports are _local_, referencing our own files rather than npm packages.
The final statement imports the CSS related to our `<App />` component. Note that there is no variable name and no `from` directive. This is called a [_side-effect import_](/en-US/docs/Web/JavaScript/Reference/Statements/import#import_a_module_for_its_side_effects_only) β it doesn't import any value into the JavaScript file, but it tells Vite to add the referenced CSS file to the final code output, so that it can be used in the browser.
### The `App()` function
After the imports, we have a function named `App()`, which defines the structure of the `App` component. Whereas most of the JavaScript community prefers {{Glossary("camel_case", "lower camel case")}} names like `helloWorld`, React components use Pascal case (or upper camel case) variable names, like `HelloWorld`, to make it clear that a given JSX element is a React component and not a regular HTML tag. If you were to rename the `App()` function to `app()`, your browser would throw an error.
Let's look at `App()` more closely.
```jsx
function App() {
const [count, setCount] = useState(0);
return (
<>
<div>
<a href="https://vitejs.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => setCount((count) => count + 1)}>
count is {count}
</button>
<p>
Edit <code>src/App.jsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
);
}
```
The `App()` function returns a JSX expression. This expression defines what your browser ultimately renders to the DOM.
Just under the `return` keyword is a special bit of syntax: `<>`. This is a [fragment](https://react.dev/reference/react/Fragment). React components have to return a single JSX element, and fragments allow us to do that without rendering arbitrary `<div>`s in the browser. You'll see fragments in many React applications.
### The `export` statement
There's one more line of code after the `App()` function:
```jsx
export default App;
```
This export statement makes our `App()` function available to other modules. We'll talk more about this later.
## Moving on to `main`
Let's open `src/main.jsx`, because that's where the `<App />` component is being used. This file is the entry point for our app, and it initially looks like this:
```jsx
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App.jsx";
import "./index.css";
ReactDOM.createRoot(document.getElementById("root")).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
```
As with `App.jsx`, the file starts by importing all the JS modules and other assets it needs to run.
The first two statements import the `React` and `ReactDOM` libraries because they are referenced later in the file. We don't write a path or extension when importing these libraries because they are not local files. In fact, they are listed as dependencies in our `package.json` file. Be careful of this distinction as you work through this lesson!
We then import our `App()` function and `index.css`, which holds global styles that are applied to our whole app.
We then call the `ReactDOM.createRoot()` function, which defines the root node of our application. This takes as an argument the DOM element inside which we want our React app to be rendered. In this case, that's the DOM element with an ID of `root`. Finally, we chain the `render()` method onto the `createRoot()` call, passing it the JSX expression that we want to render inside our root. By writing `<App />` as this JSX expression, we're telling React to call the `App()` _function_ which renders the `App` _component_ inside the root node.
> **Note:** `<App />` is rendered inside a special `<React.StrictMode>` component. This component helps developers catch potential problems in their code.
You can read up on these React APIs, if you'd like:
- [`ReactDOM.createRoot()`](https://react.dev/reference/react-dom/client/createRoot)
- [`React.StrictMode`](https://react.dev/reference/react/StrictMode)
## Starting fresh
Before we start building our app, we're going to delete some of the boilerplate code that Vite provided for us.
First, as an experiment, change the [`<h1>`](/en-US/docs/Web/HTML/Element/Heading_Elements) element in `App.jsx` so that it reads "Hello, World!", then save your file. You'll notice that this change is immediately rendered in the development server running at `http://localhost:3000` in your browser. Bear this in mind as you work on your app.
We won't be using the rest of the code! Replace the contents of `App.jsx` with the following:
```jsx
import "./App.css";
function App() {
return (
<>
<header>
<h1>Hello, World!</h1>
</header>
</>
);
}
export default App;
```
## Practice with JSX
Next, we'll use our JavaScript skills to get a bit more comfortable writing JSX and working with data in React. We'll talk about how to add attributes to JSX elements, how to write comments, how to render content from variables and other expressions, and how to pass data into components with props.
### Adding attributes to JSX elements
JSX elements can have attributes, just like HTML elements. Try adding a `<button>` below the `<h1>` element in your `App.jsx` file, like this:
```jsx
<button type="button">Click me!</button>
```
When you save your file, you'll see a button with the words `Click me!`. The button doesn't do anything yet, but we'll learn about adding interactivity to our app soon.
Some attributes are different than their HTML counterparts. For example, the `class` attribute in HTML translates to `className` in JSX. This is because `class` is a reserved word in JavaScript, and JSX is a JavaScript extension. If you wanted to add a `primary` class to your button, you'd write it like this:
```jsx
<button type="button" className="primary">
Click me!
</button>
```
### JavaScript expressions as content
Unlike HTML, JSX allows us to write variables and other JavaScript expressions right alongside our other content. Let's declare a variable called `subject` just above the `App()` function:
```jsx
const subject = "React";
function App() {
// code omitted for brevity
}
```
Next, replace the word "World" in the `<h1>` element with `{subject}`:
```jsx
<h1>Hello, {subject}!</h1>
```
Save your file and check your browser. You should see "Hello, React!" rendered.
The curly braces around `subject` are another feature of JSX's syntax. The curly braces tell React that we want to read the value of the `subject` variable, rather than render the literal string `"subject"`. You can put any valid JavaScript expression inside curly braces in JSX; React will evaluate it and render the _result_ of the expression as the final content. Following is a series of examples, with comments above explaining what each expression will render:
```jsx-nolint
{/* Hello, React :)! */}
<h1>Hello, {subject + ' :)'}!</h1>
{/* Hello, REACT */}
<h1>Hello, {subject.toUpperCase()}</h1>
{/* Hello, 4 */}
<h1>Hello, {2 + 2}!</h1>
```
Even comments in JSX are written inside curly braces! This is because comments, too, are technically JavaScript expressions. The `/* block comment syntax */` is necessary for your program to know where the comment starts and ends.
### Component props
**Props** are a means of passing data into a React component. Their syntax is identical to that of attributes, in fact: `prop="value"`. The difference is that whereas attributes are passed into plain elements, props are passed into React components.
In React, the flow of data is unidirectional: props can only be passed from parent components down to child components.
Let's open `main.jsx` and give our `<App />` component its first prop.
Add a prop of `subject` to the `<App />` component call, with a value of `Clarice`. When you are done, it should look something like this:
```jsx
<App subject="Clarice" />
```
Back in `App.jsx`, let's revisit the `App()` function. Change the signature of `App()` so that it accepts `props` as a parameter and log `props` to the console so you can inspect it. Also delete the `subject` const; we don't need it anymore. Your `App.jsx` file should look like this:
```jsx
function App(props) {
console.log(props);
return (
// code omitted for brevity
);
}
```
Save your file and check your browser. You'll see a blank background with no content. This is because we're trying to read a `subject` variable that's no longer defined. Fix this by commenting out the `<h1>Hello {subject}!</h1>` line.
> **Note:** If your code editor understands how to parse JSX (most modern editors do!), you can use its built-in commenting shortcut β `Ctrl + /` (on Windows) or `Cmd + /` (on macOS) β to create comments more quickly.
Save the file with that line commented out. This time, you should see your
"Click me!" button rendered by itself. If you open your browser's developer console, you'll see a message that looks like this:
```plain
Object { subject: "Clarice" }
```
The object property `subject` corresponds to the `subject` prop we added to our `<App />` component call, and the string `Clarice` corresponds to its value. Component props in React are always collected into objects in this fashion.
Let's use this `subject` prop to fix the error in our app. Uncomment the `<h1>Hello, {subject}!</h1>` line and change it to `<h1>Hello, {props.subject}!</h1>`, then delete the `console.log()` statement. Your code should look like this:
```jsx
function App(props) {
return (
<>
<header>
<h1>Hello, {props.subject}!</h1>
<button type="button" className="primary">
Click me!
</button>
</header>
</>
);
}
```
When you save, the app should now greet you with "Hello, Clarice!". If you return to `main.jsx`, edit the value of `subject`, and save, your text will change.
For additional practice, you could try adding an additional `greeting` prop to the `<App />` component call inside `main.jsx` and using it alongside the `subject` prop inside `App.jsx`.
## Summary
This brings us to the end of our initial look at React, including how to install it locally, creating a starter app, and how the basics work. In the next article, we'll start building our first proper application β a todo list. Before we do that, however, let's recap some of the things we've learned.
In React:
- Components can import modules they need and must export themselves at the bottom of their files.
- Component functions are named with `PascalCase`.
- You can render JavaScript expressions in JSX by putting them between curly braces, like `{so}`.
- Some JSX attributes are different than HTML attributes so that they don't conflict with JavaScript reserved words. For example, `class` in HTML translates to `className` in JSX.
- Props are written just like attributes inside component calls and are passed into components.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/ember_resources/index.md | ---
title: Ember resources and troubleshooting
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Our final Ember article provides you with a list of resources that you can use to go further in your learning, plus some useful troubleshooting and other information.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
A deeper understanding of modern JavaScript features (such as classes,
modules, etc.), will be extremely beneficial, as Ember makes heavy use
of them.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To provide further resource links and troubleshooting information.
</td>
</tr>
</tbody>
</table>
## Further resources
- [Ember.JS Guides](https://guides.emberjs.com/release/)
- [Tutorial: Super Rentals](https://guides.emberjs.com/release/tutorial/part-1/)
- [Ember.JS API Documentation](https://api.emberjs.com/ember/release)
- [Ember.JS Discord Server](https://discord.com/invite/emberjs) β a forum/chat server where you can meet the Ember community, ask for help, and help others!
## General troubleshooting, gotchas, and misconceptions
This is nowhere near an extensive list, but it is a list of things that came up around the time of writing (latest update, May 2020).
### How do I debug what's going on in the framework?
For _framework-specific_ things, there is the [ember-inspector add-on](https://guides.emberjs.com/release/ember-inspector/), which allows inspection of:
- Routes & Controllers
- Components
- Services
- Promises
- Data (i.e., from a remote API β from ember-data, by default)
- Deprecation Information
- Render Performance
For general JavaScript debugging, check out our [guides on JavaScript Debugging](https://firefox-source-docs.mozilla.org/devtools-user/debugger/index.html)
as well as interacting with the [browser's other debugging tools](https://firefox-source-docs.mozilla.org/devtools-user/index.html). In any default Ember
project, there will be two main JavaScript files, `vendor.js` and `{app-name}.js`. Both of
these files are generated with sourcemaps, so when you open the `vendor.js` or `{app-name}.js` to search for relevant code, when a debugger is placed, the sourcemap will be loaded and the breakpoint will be placed in the pre-transpiled code for easier correlation to your project code.
For more information on sourcemaps, why they're needed, and what the ember-cli does with them, see the [Advanced Use: Asset Compilation](https://cli.emberjs.com/release/advanced-use/asset-compilation/) guide. Note that sourcemaps are enabled by default.
### `ember-data` comes pre-installed; do I need it?
Not at all. While `ember-data` solves _the most common problems_ that any app dealing with
data will run in to, it is possible to roll your own front-end data client. A common
alternative is to any fully-featured front-end data client is [The Fetch API](/en-US/docs/Web/API/Fetch_API/Using_Fetch).
Using the design patterns provided by the framework, a `Route` using `fetch()` would look something like this:
```js
import Route from "@ember/routing/route";
export default class MyRoute extends Route {
async model() {
let response = await fetch("some/url/to/json/data");
let json = await response.json();
return {
data: json,
};
}
}
```
See more information on [specifying the `Route`'s model](https://guides.emberjs.com/release/routing/specifying-a-routes-model/) here.
### Why can't I just use JavaScript?
This is the _most_ common question Ember folks hear from people who have previous
experience with [React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started). While it is technically possible to use JSX, or any
other form of DOM creation, there has yet to be anything as robust as Ember's
templating system. The intentional minimalism forces certain decisions, and allows
for more consistent code, while keeping the template more structural rather than having them filled with bespoke logic.
See also: [ReactiveConf 2017: Secrets of the Glimmer VM](https://www.youtube.com/watch?v=nXCSloXZ-wc)
### What is the state of the `mut` helper?
`mut` was not covered in this tutorial and is really baggage from a transitional time when Ember was moving from two-way bound data to the more common and easier-to-reason-about one-way bound data flow. It could be thought of as a build-time transform that wraps its argument with a setter function.
More concretely, using `mut` allows for template-only settings functions to be declared:
```hbs-nolint
<Checkbox
@value=\{{this.someData}}
@onToggle=\{{fn (mut this.someData) (not this.someData)}}
/>
```
Whereas, without `mut`, a component class would be needed:
```js
import Component from "@glimmer/component";
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";
export default class Example extends Component {
@tracked someData = false;
@action
setData(newValue) {
this.someData = newValue;
}
}
```
Which would then be called in the template like so:
```hbs-nolint
<Checkbox @data=\{{this.someData}} @onChange=\{{this.setData}} />
```
Due to the conciseness of using `mut`, it may be desirable to reach for it. However, `mut` has unnatural semantics and has caused much confusion over the term of its existence.
There have been a couple of new ideas put together into the form of addons that use the public APIs, [`ember-set-helper`](https://github.com/pzuraq/ember-set-helper) and [`ember-box`](https://github.com/pzuraq/ember-box). Both of these try to solve the problems of `mut`
by introducing more obvious / "less magic" concepts, avoiding build-time transforms and
implicit Glimmer VM behavior.
With `ember-set-helper`:
```hbs
<Checkbox @value=\{{this.someData}} @onToggle=\{{set this "someData" (not
this.someData)}} />
```
With `ember-box`:
```hbs-nolint
\{{#let (box this.someData) as |someData|}}
<Checkbox
@value=\{{unwrap someData}}
@onToggle=\{{update someData (not this.someData)}}
/>
\{{/let}}
```
Note that none of these solutions are particularly common among members of the community, and as a whole, people are still trying to figure out an ergonomic and simple API for setting data in a template-only context, without backing JS.
### What is the purpose of Controllers?
[Controllers](https://guides.emberjs.com/release/routing/controllers/) are [Singletons](https://en.wikipedia.org/wiki/Singleton_pattern), which may help manage the rendering context of the
active route. On the surface, they function much the same as the backing JavaScript of a Component. Controllers are (as of January 2020), the only way to manage URL Query Params.
Ideally, controllers should be fairly light in their responsibilities, delegating to Components
and Services where possible.
### What is the purpose of Routes?
A [Route](https://guides.emberjs.com/release/routing/defining-your-routes/) represents part of the URL when a user navigates from place to place in the app.
A Route has only a couple responsibilities:
- Load the _minimally required data_ to render the route (or view-sub-tree).
- Gate access to the route and redirect if needed.
- Handle loading and error states from the minimally required data.
A Route only has 3 lifecycle hooks, all of which are optional:
- `beforeModel` β gate access to the route.
- `model` β where data is loaded.
- `afterModel` β verify access.
Last, a Route has the ability to handle common events resulting from configuring the `model`:
- `loading` β what to do when the `model` hook is loading.
- `error` β what to do when an error is thrown from `model`.
Both `loading` and `error` can render default templates as well as customized templates defined elsewhere in the application, unifying loading/error states.
More information on [everything a Route can do is found in the API documentation](https://api.emberjs.com/ember/release/classes/Route/).
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/react_resources/index.md | ---
title: React resources
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Our final article provides you with a list of React resources that you can use to go further in your learning.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To provide further resources for learning more about React.</td>
</tr>
</tbody>
</table>
## Component-level styles
While we kept all the CSS for our tutorial in a single `index.css` file, it's common for React applications to define per-component stylesheets. In an application powered by Vite, this can be done by creating a CSS file and importing it into its corresponding component module.
For example: we could have written a dedicated `Form.css` file to house the CSS related to the `<Form />` component, then imported the styles into `Form.jsx`, like this:
```jsx
import Form from "./Form";
import "./Form.css";
```
This approach makes it easy to identify and manage the CSS that belongs to a specific component and distinguish it from your app-wide styles. However, it also fragments your stylesheet across your codebase, and this fragmentation might not be worthwhile. For larger applications with hundreds of unique views and lots of moving parts, it makes sense to use component-level styles and thereby limit the amount of irrelevant code that's sent to your user at any one time.
You can read more about this and other approaches to styling React components in the Smashing Magazine article, [Styling Components In React](https://www.smashingmagazine.com/2020/05/styling-components-react/).
## React DevTools
We used `console.log()` to check on the state and props of our application in this tutorial, and you'll also have seen some of the useful warnings and error message that React gives you both in the CLI and your browser's JavaScript console. But there's more we can do here.
The React DevTools utility allows you to inspect the internals of your React application directly in the browser. It adds a new panel to your browser's developer tools that allows you to inspect the state and props of various components, and even edit state and props to make immediate changes to your application.
This screenshot shows our finished application as it appears in React DevTools:

On the left, we see all of the components that make up our application, including unique keys for the items that are rendered from arrays. On the right, we see the props and hooks that our App component uses. Notice, too, that the `Form`, `FilterButton`, and `Todo` components are indented to the right β this indicates that `App` is their parent. This view is great for understanding parent/child relationships at a glance and is invaluable for understanding more complex apps.
React DevTools is available in several forms:
- A [Chrome browser extension](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi?hl=en).
- A [Firefox browser extension](https://addons.mozilla.org/en-US/firefox/addon/react-devtools/).
- A [Microsoft Edge browser extension](https://microsoftedge.microsoft.com/addons/detail/react-developer-tools/gpphkfbcpidddadnkolkpfckpihlkkil).
- A [stand-alone application you can install with npm or Yarn](https://www.npmjs.com/package/react-devtools).
Try installing one of these, and then using it to inspect the app you've just built!
You can [read more about React DevTools in the React docs](https://react.dev/learn/react-developer-tools).
## The `useReducer()` hook
In this tutorial, we used the `useState()` hook to manage state across a small collection of event handler functions. This was fine for learning purposes, but it left our state management logic tied to our component's event handlers β especially those of the `<Todo />` component.
The `useReducer()` hook offers developers a way to consolidate different-but-related state management logic into a single function. It's a bit more complex than `useState()`, but it's a good tool to have in your belt. You can [read more about `useReducer()` in the React docs](https://react.dev/learn/extracting-state-logic-into-a-reducer).
## The Context API
The application that we built in this tutorial utilized component props to pass data from its `App` component to the child components that needed it. Most of the time, props are an appropriate method for sharing data; for complex, deeply nested applications, however, they're not always best.
React provides the [Context API](https://react.dev/learn/passing-data-deeply-with-context) as a way to provide data to components that need it _without_ passing props down the component tree. There's also [a useContext hook](https://react.dev/reference/react/useContext) that facilitates this.
If you'd like to try this API for yourself, Smashing Magazine has written an [introductory article about React context](https://www.smashingmagazine.com/2020/01/introduction-react-context-api/).
## Class components
Although this tutorial doesn't mention them, it is possible to build React components using [JavaScript classes](/en-US/docs/Web/JavaScript/Reference/Classes) β these are called class components. Until the arrival of hooks, classes were the only way to bring state into components or manage rendering side effects. They're still the only way to handle certain edge-cases, and they're common in legacy React projects. The official React docs maintain a reference for the [`Component`](https://react.dev/reference/react/Component) base class, but recommend using hooks to manage [state](https://react.dev/learn/state-a-components-memory) and [side effects](https://react.dev/learn/synchronizing-with-effects).
## Testing
Libraries such as [React Testing Library](https://testing-library.com/docs/react-testing-library/intro/) make it possible to write unit tests for React components. There are many ways to _run_ these tests. The testing framework [Vitest](https://vitest.dev/) is built on top of Vite, and is a great companion to your Vite-powered React applications. [Jest](https://jestjs.io/) is another popular testing framework that can be used with React.
## Routing
While routing is traditionally handled by a server and not an application on the user's computer, it is possible to configure a web application to read and update the browser's location, and render certain user interfaces. This is called _client-side routing_. It's possible to create many unique routes for your application (such as `/home`, `/dashboard`, or `/login`).
[React Router](https://reactrouter.com/) is the most popular and most robust client-side routing library for React. It allows developers to define the routes of their application, and associate components with those routes . It also provides a number of useful hooks and components for managing the browser's location and history.
> **Note:** Client-side routing can make your application feel fast, but it poses a number of accessibility problems, especially for people who rely on assistive techology. You can read more about this in Marcy Sutton's article, ["The Implications of Client-Side Routing"](https://testingaccessibility.com/implications-of-client-side-routing).
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/react_todo_list_beginning/index.md | ---
title: Beginning our React todo list
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_todo_list_beginning
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Let's say that we've been tasked with creating a proof-of-concept in React β an app that allows users to add, edit, and delete tasks they want to work on, and also mark tasks as complete without deleting them. This article will walk you through the basic structure and styling of such an application, ready for individual component definition and interactivity, which we'll add later.
> **Note:** If you need to check your code against our version, you can find a finished version of the sample React app code in our [todo-react repository](https://github.com/mdn/todo-react). For a running live version, see <https://mdn.github.io/todo-react/>.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To introduce our todo list case study, and get the basic
<code>App</code> structure and styling in place.
</td>
</tr>
</tbody>
</table>
## Our app's user stories
In software development, a user story is an actionable goal from the perspective of the user. Defining user stories before we begin our work will help us focus our work. Our app should fulfill the following stories:
As a user, I can
- read a list of tasks.
- add a task using the mouse or keyboard.
- mark any task as completed, using the mouse or keyboard.
- delete any task, using the mouse or keyboard.
- edit any task, using the mouse or keyboard.
- view a specific subset of tasks: All tasks, only the active task, or only the completed tasks.
We'll tackle these stories one-by-one.
## Pre-project housekeeping
Vite has given us some code that we won't be using at all for our project. The following terminal commands will delete it to make way for our new project. Make sure you're starting in the app's root directory!
```bash
# Move into the src directory
cd src
# Delete the App.css file and the React logo provided by Vite
rm App.css assets/react.svg
# Empty the contents of App.jsx and index.css
echo -n > App.jsx && echo -n > index.css
# Move back up to the root of the project
cd ..
```
> **Note:** If you stopped your server to do the terminal tasks mentioned above, you'll have to start it again using `npm run dev`.
## Project starter code
As a starting point for this project, we're going to provide two things: an `App()` function to replace the one you just deleted, and some CSS to style your app.
### The JSX
Copy the following snippet to your clipboard, then paste it into `App.jsx`:
```jsx
function App(props) {
return (
<div className="todoapp stack-large">
<h1>TodoMatic</h1>
<form>
<h2 className="label-wrapper">
<label htmlFor="new-todo-input" className="label__lg">
What needs to be done?
</label>
</h2>
<input
type="text"
id="new-todo-input"
className="input input__lg"
name="text"
autoComplete="off"
/>
<button type="submit" className="btn btn__primary btn__lg">
Add
</button>
</form>
<div className="filters btn-group stack-exception">
<button type="button" className="btn toggle-btn" aria-pressed="true">
<span className="visually-hidden">Show </span>
<span>all</span>
<span className="visually-hidden"> tasks</span>
</button>
<button type="button" className="btn toggle-btn" aria-pressed="false">
<span className="visually-hidden">Show </span>
<span>Active</span>
<span className="visually-hidden"> tasks</span>
</button>
<button type="button" className="btn toggle-btn" aria-pressed="false">
<span className="visually-hidden">Show </span>
<span>Completed</span>
<span className="visually-hidden"> tasks</span>
</button>
</div>
<h2 id="list-heading">3 tasks remaining</h2>
<ul
role="list"
className="todo-list stack-large stack-exception"
aria-labelledby="list-heading">
<li className="todo stack-small">
<div className="c-cb">
<input id="todo-0" type="checkbox" defaultChecked />
<label className="todo-label" htmlFor="todo-0">
Eat
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">Eat</span>
</button>
<button type="button" className="btn btn__danger">
Delete <span className="visually-hidden">Eat</span>
</button>
</div>
</li>
<li className="todo stack-small">
<div className="c-cb">
<input id="todo-1" type="checkbox" />
<label className="todo-label" htmlFor="todo-1">
Sleep
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">Sleep</span>
</button>
<button type="button" className="btn btn__danger">
Delete <span className="visually-hidden">Sleep</span>
</button>
</div>
</li>
<li className="todo stack-small">
<div className="c-cb">
<input id="todo-2" type="checkbox" />
<label className="todo-label" htmlFor="todo-2">
Repeat
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">Repeat</span>
</button>
<button type="button" className="btn btn__danger">
Delete <span className="visually-hidden">Repeat</span>
</button>
</div>
</li>
</ul>
</div>
);
}
export default App;
```
Now open `index.html` and change the [`<title>`](/en-US/docs/Web/HTML/Element/title) element's text to `TodoMatic`. This way, it will match the [`<h1>`](/en-US/docs/Web/HTML/Element/Heading_Elements) at the top of our app.
```html
<title>TodoMatic</title>
```
When your browser refreshes, you should see something like this:

It's ugly, and doesn't function yet, but that's okay β we'll style it in a moment. First, consider the JSX we have, and how it corresponds to our user stories:
- We have a [`<form>`](/en-US/docs/Web/HTML/Element/form) element, with an [`<input type="text">`](/en-US/docs/Web/HTML/Element/input/text) for writing out a new task, and a button to submit the form.
- We have an array of buttons that will be used to filter our tasks.
- We have a heading that tells us how many tasks remain.
- We have our 3 tasks, arranged in an unordered list. Each task is a list item ([`<li>`](/en-US/docs/Web/HTML/Element/li)), and has buttons to edit and delete it and a checkbox to check it off as done.
The form will allow us to _make_ tasks; the buttons will let us _filter_ them; the heading and list are our way to _read_ them. The UI for _editing_ a task is conspicuously absent for now. That's okay β we'll write that later.
### Accessibility features
You may notice some unusual markup here. For example:
```jsx
<button type="button" className="btn toggle-btn" aria-pressed="true">
<span className="visually-hidden">Show </span>
<span>all</span>
<span className="visually-hidden"> tasks</span>
</button>
```
Here, `aria-pressed` tells assistive technology (like screen readers) that the button can be in one of two states: `pressed` or `unpressed`. Think of these as analogs for `on` and `off`. Setting a value of `"true"` means that the button is pressed by default.
The class `visually-hidden` has no effect yet, because we have not included any CSS. Once we have put our styles in place, though, any element with this class will be hidden from sighted users and still available to assistive technology users β this is because these words are not needed by sighted users; they are there to provide more information about what the button does for assistive technology users that do not have the extra visual context to help them.
Further down, you can find our [`<ul>`](/en-US/docs/Web/HTML/Element/ul) element:
```html
<ul
role="list"
className="todo-list stack-large stack-exception"
aria-labelledby="list-heading">
β¦
</ul>
```
The `role` attribute helps assistive technology explain what kind of element a tag represents. A `<ul>` is treated like a list by default, but the styles we're about to add will break that functionality. This role will restore the "list" meaning to the `<ul>` element. If you want to learn more about why this is necessary, you can check out [Scott O'Hara's article, "Fixing Lists"](https://www.scottohara.me/blog/2019/01/12/lists-and-safari.html).
The `aria-labelledby` attribute tells assistive technologies that we're treating our list heading as the label that describes the purpose of the list beneath it. Making this association gives the list a more informative context, which could help assistive technology users better understand the list's purpose.
Finally, the labels and inputs in our list items have some attributes unique to JSX:
```jsx
<input id="todo-0" type="checkbox" defaultChecked />
<label className="todo-label" htmlFor="todo-0">
Eat
</label>
```
The `defaultChecked` attribute in the `<input />` tag tells React to check this checkbox initially. If we were to use `checked`, as we would in regular HTML, React would log some warnings into our browser console relating to handling events on the checkbox, which we want to avoid. Don't worry too much about this for now β we will cover this later on when we get to using events.
The `htmlFor` attribute corresponds to the `for` attribute used in HTML. We cannot use `for` as an attribute in JSX because `for` is a reserved word, so React uses `htmlFor` instead.
### A note on boolean attributes in JSX
The `defaultChecked` attribute in the previous section is a boolean attribute β an attribute whose value is either `true` or `false`. Like in HTML, a boolean attribute is `true` if it's present and `false` if it's absent; the assignment on the right-hand side of the expression is optional. You can explicitly set its value by passing it in curly braces β for example, `defaultChecked={true}` or `defaultChecked={false}`.
Because JSX is JavaScript, there's a gotcha to be aware of with boolean attributes: writing `defaultChecked="false"` will set a _string_ value of `"false"` rather than a _boolean_ value. Non-empty strings are [truthy](/en-US/docs/Glossary/Truthy), so React will consider `defaultChecked` to be `true` and check the checkbox by default. This is not what we want, so we should avoid it.
If you'd like, you can practice writing boolean attributes with another attribute you may have seen before, [`hidden`](/en-US/docs/Web/HTML/Global_attributes/hidden), which prevents elements from being rendered on the page. Try adding `hidden` to the `<h1>` element in `App.jsx` to see what happens, then try explicitly setting its value to `{false}`. Note, again, that writing `hidden="false"` results in a truthy value so the `<h1>` _will_ hide. Don't forget to remove this code when you're done.
> **Note:** The `aria-pressed` attribute used in our earlier code snippet has a value of `"true"` because `aria-pressed` is not a true boolean attribute in the way `checked` is.
### Implementing our styles
Paste the following CSS code into `src/index.css`:
```css
/* Resets */
*,
*::before,
*::after {
box-sizing: border-box;
}
*:focus-visible {
outline: 3px dashed #228bec;
outline-offset: 0;
}
html {
font: 62.5% / 1.15 sans-serif;
}
h1,
h2 {
margin-bottom: 0;
}
ul {
list-style: none;
padding: 0;
}
button {
-moz-osx-font-smoothing: inherit;
-webkit-font-smoothing: inherit;
appearance: none;
background: transparent;
border: none;
color: inherit;
font: inherit;
line-height: normal;
margin: 0;
overflow: visible;
padding: 0;
width: auto;
}
button::-moz-focus-inner {
border: 0;
}
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
font-size: 100%;
line-height: 1.15;
margin: 0;
}
button,
input {
overflow: visible;
}
input[type="text"] {
border-radius: 0;
}
body {
background-color: #f5f5f5;
color: #4d4d4d;
font:
1.6rem/1.25 Arial,
sans-serif;
margin: 0 auto;
max-width: 68rem;
width: 100%;
}
@media screen and (min-width: 620px) {
body {
font-size: 1.9rem;
line-height: 1.31579;
}
}
/* End resets */
/* Global styles */
.form-group > input[type="text"] {
display: inline-block;
margin-top: 0.4rem;
}
.btn {
border: 0.2rem solid #4d4d4d;
cursor: pointer;
padding: 0.8rem 1rem 0.7rem;
text-transform: capitalize;
}
.btn.toggle-btn {
border-color: #d3d3d3;
border-width: 1px;
}
.btn.toggle-btn[aria-pressed="true"] {
border-color: #4d4d4d;
text-decoration: underline;
}
.btn__danger {
background-color: #ca3c3c;
border-color: #bd2130;
color: #fff;
}
.btn__filter {
border-color: lightgrey;
}
.btn__primary {
background-color: #000;
color: #fff;
}
.btn-group {
display: flex;
justify-content: space-between;
}
.btn-group > * {
flex: 1 1 49%;
}
.btn-group > * + * {
margin-left: 0.8rem;
}
.label-wrapper {
flex: 0 0 100%;
margin: 0;
text-align: center;
}
.visually-hidden {
clip: rect(1px 1px 1px 1px);
clip: rect(1px, 1px, 1px, 1px);
height: 1px;
overflow: hidden;
position: absolute !important;
white-space: nowrap;
width: 1px;
}
[class*="stack"] > * {
margin-bottom: 0;
margin-top: 0;
}
.stack-small > * + * {
margin-top: 1.25rem;
}
.stack-large > * + * {
margin-top: 2.5rem;
}
@media screen and (min-width: 550px) {
.stack-small > * + * {
margin-top: 1.4rem;
}
.stack-large > * + * {
margin-top: 2.8rem;
}
}
.stack-exception {
margin-top: 1.2rem;
}
/* End global styles */
/* General app styles */
.todoapp {
background: #fff;
box-shadow:
0 2px 4px 0 rgb(0 0 0 / 20%),
0 2.5rem 5rem 0 rgb(0 0 0 / 10%);
margin: 2rem 0 4rem 0;
padding: 1rem;
position: relative;
}
@media screen and (min-width: 550px) {
.todoapp {
padding: 4rem;
}
}
.todoapp > * {
margin-left: auto;
margin-right: auto;
max-width: 50rem;
}
.todoapp > form {
max-width: 100%;
}
.todoapp > h1 {
display: block;
margin: 0;
margin-bottom: 1rem;
max-width: 100%;
text-align: center;
}
.label__lg {
line-height: 1.01567;
font-weight: 300;
margin-bottom: 1rem;
padding: 0.8rem;
text-align: center;
}
.input__lg {
border: 2px solid #000;
padding: 2rem;
}
.input__lg:focus-visible {
border-color: #4d4d4d;
box-shadow: inset 0 0 0 2px;
}
[class*="__lg"] {
display: inline-block;
font-size: 1.9rem;
width: 100%;
}
[class*="__lg"]:not(:last-child) {
margin-bottom: 1rem;
}
@media screen and (min-width: 620px) {
[class*="__lg"] {
font-size: 2.4rem;
}
}
/* End general app styles */
/* Todo item styles */
.todo {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.todo > * {
flex: 0 0 100%;
}
.todo-text {
border: 2px solid #565656;
min-height: 4.4rem;
padding: 0.4rem 0.8rem;
width: 100%;
}
.todo-text:focus-visible {
box-shadow: inset 0 0 0 2px;
}
/* End todo item styles */
/* Checkbox styles */
.c-cb {
-webkit-font-smoothing: antialiased;
box-sizing: border-box;
clear: left;
display: block;
font-family: Arial, sans-serif;
font-size: 1.6rem;
font-weight: 400;
line-height: 1.25;
min-height: 44px;
padding-left: 40px;
position: relative;
}
.c-cb > label::before,
.c-cb > input[type="checkbox"] {
box-sizing: border-box;
height: 44px;
left: -2px;
top: -2px;
width: 44px;
}
.c-cb > input[type="checkbox"] {
-webkit-font-smoothing: antialiased;
cursor: pointer;
margin: 0;
opacity: 0;
position: absolute;
z-index: 1;
}
.c-cb > label {
cursor: pointer;
display: inline-block;
font-family: inherit;
font-size: inherit;
line-height: inherit;
margin-bottom: 0;
padding: 8px 15px 5px;
touch-action: manipulation;
}
.c-cb > label::before {
background: transparent;
border: 2px solid currentcolor;
content: "";
position: absolute;
}
.c-cb > input[type="checkbox"]:focus-visible + label::before {
border-width: 4px;
outline: 3px dashed #228bec;
}
.c-cb > label::after {
background: transparent;
border: solid;
border-width: 0 0 5px 5px;
border-top-color: transparent;
box-sizing: content-box;
content: "";
height: 7px;
left: 9px;
opacity: 0;
position: absolute;
top: 11px;
transform: rotate(-45deg);
width: 18px;
}
.c-cb > input[type="checkbox"]:checked + label::after {
opacity: 1;
}
/* End checkbox styles */
```
Save and look back at your browser, and your app should now have reasonable styling.
## Summary
Now our todo list app actually looks a bit more like a real app! The problem is: it doesn't actually do anything. We'll start fixing that in the next chapter!
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/vue_getting_started/index.md | ---
title: Getting started with Vue
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Now let's introduce Vue, the third of our frameworks. In this article we'll look at a little bit of Vue background, learn how to install it and create a new project, study the high-level structure of the whole project and an individual component, see how to run the project locally, and get it prepared to start building our example.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To setup a local Vue development environment, create a starter app, and
understand the basics of how it works.
</td>
</tr>
</tbody>
</table>
## A clearer Vue
Vue is a modern JavaScript framework that provides useful facilities for progressive enhancement β unlike many other frameworks, you can use Vue to enhance existing HTML. This lets you use Vue as a drop-in replacement for a library like [jQuery](https://jquery.com/).
That being said, you can also use Vue to write entire Single Page Applications (SPAs). This allows you to create markup managed entirely by Vue, which can improve developer experience and performance when dealing with complex applications. It also allows you to take advantage of libraries for client-side routing and state management when you need to. Additionally, Vue takes a "middle ground" approach to tooling like client-side routing and state management. While the Vue core team maintains suggested libraries for these functions, they are not directly bundled into Vue. This allows you to select a different routing/state management library if they better fit your application.
In addition to allowing you to progressively integrate Vue into your applications, Vue also provides a progressive approach to writing markup. Like most frameworks, Vue lets you create reusable blocks of markup via components. Most of the time, Vue components are written using a special HTML template syntax. When you need more control than the HTML syntax allows, you can write JSX or plain JavaScript functions to define your components.
As you work through this tutorial, you might want to keep the [Vue guide](https://vuejs.org/guide/introduction.html) and [API documentation](https://vuejs.org/api/) open in other tabs, so you can refer to them if you want more information on any sub topic.
For a good (but potentially biased) comparison between Vue and many of the other frameworks, see [Vue Docs: Comparison with Other Frameworks](https://v2.vuejs.org/v2/guide/comparison.html).
## Installation
To use Vue in an existing site, you can drop one of the following [`<script>`](/en-US/docs/Web/HTML/Element/script) elements onto a page. This allows you to start using Vue on existing sites, which is why Vue prides itself on being a progressive framework. This is a great option when migrating an existing project using a library like jQuery to Vue. With this method, you can use a lot of the core features of Vue, such as the attributes, custom components, and data-management.
- Development Script (not optimized, but includes console warnings which is great for development.)
```html
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
```
- Production Script (Optimized version, minimal console warnings. It is recommended that you specify a version number when including Vue on your site so that any framework updates do not break your live site without you knowing.)
```html
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
```
However, this approach has some limitations. To build more complex apps, you'll want to use the [Vue npm package](https://www.npmjs.com/package/vue). This will let you use advanced features of Vue and take advantage of bundlers like WebPack. To make building apps with Vue easier, there is a CLI to streamline the development process. To use the npm package & the CLI you will need:
1. Node.js 8.11+ installed.
2. [npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) or [yarn](https://yarnpkg.com/).
> **Note:** If you don't have the above installed, find out [more about installing npm and Node.js](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line#adding_powerups) here.
To install the CLI, run the following command in your terminal:
```bash
npm install --global @vue/cli
```
Or if you'd prefer to use yarn:
```bash
yarn global add @vue/cli
```
Once installed, to initialize a new project you can then open a terminal in the directory you want to create the project in, and run `vue create <project-name>`. The CLI will then give you a list of project configurations you can use. There are a few preset ones, and you can make your own. These options let you configure things like TypeScript, linting, vue-router, testing, and more.
We'll look at using this below.
## Initializing a new project
To explore various features of Vue, we will be building up a sample todo list app. We'll begin by using the Vue CLI to create a new app framework to build our app into.
In terminal, `cd` to where you'd like to create your sample app, then run `vue create moz-todo-vue`.
You can choose the default option `Default ([Vue 3] babel, eslint)` by pressing <kbd>Enter</kbd> to proceed.
The CLI will now begin scaffolding out your project, and installing all of your dependencies.
If you've never run the Vue CLI before, you'll get one more question β you'll be asked to choose a package manager which defaults to `yarn`.
The Vue CLI will default to this package manager from now on. If you need to use a different package manager after this, you can pass in a flag `--packageManager=<package-manager>`, when you run `vue create`. So if you wanted to create the `moz-todo-vue` project with npm and you'd previously chosen yarn, you'd run `vue create moz-todo-vue --packageManager=npm`.
> **Note:** We've not gone over all of the options here, but you can [find more information on the CLI](https://cli.vuejs.org) in the Vue docs.
## Project structure
If everything went successfully, the CLI should have created a series of files and directories for your project. The most significant ones are as follows:
- `package.json`: This file contains the list of dependencies for your project, as well as some metadata and `eslint` configuration.
- `yarn.lock`: If you chose `yarn` as your package manager, this file will be generated with a list of all the dependencies and sub-dependencies that your project needs.
- `babel.config.js`: This is the config file for [Babel](https://babeljs.io/), which transforms modern JavaScript features being used in development code into older syntax that is more cross-browser compatible in production code. You can register additional babel plugins in this file.
- `jsconfig.json`: This is a config file for [Visual Studio Code](https://code.visualstudio.com/docs/languages/jsconfig) and gives context for VS Code on your project structure and assists auto-completion.
- `public`: This directory contains static assets that are published, but not processed by [Webpack](https://webpack.js.org/) during build (with one exception; `index.html` gets some processing).
- `favicon.ico`: This is the favicon for your app. Currently, it's the Vue logo.
- `index.html`: This is the template for your app. Your Vue app is run from this HTML page, and you can use lodash template syntax to interpolate values into it.
> **Note:** this is not the template for managing the layout of your application β this template is for managing static HTML that sits outside of your Vue app. Editing this file typically only occurs in advanced use cases.
- `src`: This directory contains the core of your Vue app.
- `main.js`: this is the entry point to your application. Currently, this file initializes your Vue application and signifies which HTML element in the `index.html` file your app should be attached to. This file is often where you register global components or additional Vue libraries.
- `App.vue`: this is the top-level component in your Vue app. See below for more explanation of Vue components.
- `components`: this directory is where you keep your components. Currently, it just has one example component.
- `assets`: this directory is for storing static assets like CSS and images. Because these files are in the source directory, they can be processed by Webpack. This means you can use pre-processors like [Sass/SCSS](https://sass-lang.com/) or [Stylus](https://stylus-lang.com/).
> **Note:** Depending on the options you select when creating a new project, there might be other directories present (for example, if you choose a router, you will also have a `views` directory).
## .vue files (single file components)
Like in many front-end frameworks, components are a central part of building apps in Vue. These components let you break a large application into discrete building blocks that can be created and managed separately, and transfer data between each other as required. These small blocks can help you reason about and test your code.
While some frameworks encourage you to separate your template, logic, and styling code into separate files, Vue takes the opposite approach. Using [Single File Components (SFC)](https://vuejs.org/guide/scaling-up/sfc.html), Vue lets you group your templates, corresponding script, and CSS all together in a single file ending in `.vue`. These files are processed by a JS build tool (such as Webpack), which means you can take advantage of build-time tooling in your project. This allows you to use tools like Babel, TypeScript, SCSS and more to create more sophisticated components.
As a bonus, projects created with the Vue CLI are configured to use `.vue` files with Webpack out of the box. In fact, if you look inside the `src` folder in the project we created with the CLI, you'll see your first `.vue` file: `App.vue`.
Let's explore this now.
### App.vue
Open your `App.vue` file β you'll see that it has three parts: `<template>`, `<script>`, and `<style>`, which contain the component's template, scripting, and styling information. All Single File Components share this same basic structure.
`<template>` contains all the markup structure and display logic of your component. Your template can contain any valid HTML, as well as some Vue-specific syntax that we'll cover later.
> **Note:** By setting the `lang` attribute on the `<template>` tag, you can use Pug template syntax instead of standard HTML β `<template lang="pug">`. We'll stick to standard HTML through this tutorial, but it is worth knowing that this is possible.
`<script>` contains all of the non-display logic of your component. Most importantly, your `<script>` tag needs to have a default exported JS object. This object is where you locally register components, define component inputs (props), handle local state, define methods, and more. Your build step will process this object and transform it (with your template) into a Vue component with a `render()` function.
In the case of `App.vue`, our default export sets the name of the component to `App` and registers the `HelloWorld` component by adding it into the `components` property. When you register a component in this way, you're registering it locally. Locally registered components can only be used inside the components that register them, so you need to import and register them in every component file that uses them. This can be useful for bundle splitting/tree shaking since not every page in your app necessarily needs every component.
```js
import HelloWorld from "./components/HelloWorld.vue";
export default {
name: "App",
components: {
//You can register components locally here.
HelloWorld,
},
};
```
> **Note:** If you want to use [TypeScript](https://www.typescriptlang.org/) syntax, you need to set the `lang` attribute on the `<script>` tag to signify to the compiler that you're using TypeScript β `<script lang="ts">`.
`<style>` is where you write your CSS for the component. If you add a `scoped` attribute β `<style scoped>` β Vue will scope the styles to the contents of your SFC. This works similar to CSS-in-JS solutions, but allows you to just write plain CSS.
> **Note:** If you select a CSS pre-processor when creating the project via the CLI, you can add a `lang` attribute to the `<style>` tag so that the contents can be processed by Webpack at build time. For example, `<style lang="scss">` will allow you to use SCSS syntax in your styling information.
## Running the app locally
The Vue CLI comes with a built-in development server. This allows you to run your app locally so you can test it easily without needing to configure a server yourself. The CLI adds a `serve` command to the project's `package.json` file as an npm script, so you can easily run it.
In your terminal, try running `npm run serve` (or `yarn serve` if you prefer yarn). Your terminal should output something like the following:
```plain
INFO Starting development server...
98% after emitting CopyPlugin
DONE Compiled successfully in 18121ms
App running at:
- Local: <http://localhost:8080/>
- Network: <http://192.168.1.9:8080/>
Note that the development build is not optimized.
To create a production build, run npm run build.
```
If you navigate to the "local" address in a new browser tab (this should be something like `http://localhost:8080` as stated above, but may vary based on your setup), you should see your app. Right now, it should contain a welcome message, a link to the Vue documentation, links to the plugins you added when you initialized the app with your CLI, and some other useful links to the Vue community and ecosystem.

## Making a couple of changes
Let's make our first change to the app β we'll delete the Vue logo. Open the `App.vue` file, and delete the [`<img>`](/en-US/docs/Web/HTML/Element/img) element from the template section:
```html
<img alt="Vue logo" src="./assets/logo.png" />
```
If your server is still running, you should see the logo removed from the rendered site almost instantly. Let's also remove the `HelloWorld` component from our template.
First of all delete this line:
```html
<HelloWorld msg="Welcome to Your Vue.js App" />
```
If you save your `App.vue` file now, the rendered app will throw an error because we've registered the component but are not using it. We also need to remove the lines from inside the `<script>` element that import and register the component:
Delete these lines now:
```js
import HelloWorld from "./components/HelloWorld.vue";
```
```js
components: {
HelloWorld;
}
```
The `<template>` tag is empty now so you'll see an error saying `The template requires child element` in both the console and the rendered app.
You can fix this by adding some content inside the `<template>` tag and we can start with a new `<h1>` element inside a `<div>`.
Since we're going to be creating a todo list app below, let's set our heading to "To-Do List" like so:
```html
<template>
<div id="app">
<h1>To-Do List</h1>
</div>
</template>
```
`App.vue` will now show our heading, as you'd expect.
## Summary
Let's leave this here for now. We've learnt about some of the ideas behind Vue, created some scaffolding for our example app to live inside, inspected it, and made a few preliminary changes.
With a basic introduction out of the way, we'll now go further and build up our sample app, a basic Todo list application that allows us to store a list of items, check them off when done, and filter the list by all, complete, and incomplete todos.
In the next article we'll build our first custom component, and look at some important concepts such as passing props into it and saving its data state.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/react_interactivity_filtering_conditional_rendering/index.md | ---
title: "React interactivity: Editing, filtering, conditional rendering"
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
As we near the end of our React journey (for now at least), we'll add the finishing touches to the main areas of functionality in our Todo list app. This includes allowing you to edit existing tasks, and filtering the list of tasks between all, completed, and incomplete tasks. We'll look at conditional UI rendering along the way.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn about conditional rendering in React, and implementing list
filtering and an editing UI in our app.
</td>
</tr>
</tbody>
</table>
## Editing the name of a task
We don't have a user interface for editing the name of a task yet. We'll get to that in a moment. To start with, we can at least implement an `editTask()` function in `App.jsx`. It'll be similar to `deleteTask()` because it'll take an `id` to find its target object, but it'll also take a `newName` property containing the name to update the task to. We'll use [`Array.prototype.map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) instead of [`Array.prototype.filter()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) because we want to return a new array with some changes, instead of deleting something from the array.
Add the `editTask()` function inside your `<App />` component, in the same place as the other functions:
```jsx
function editTask(id, newName) {
const editedTaskList = tasks.map((task) => {
// if this task has the same ID as the edited task
if (id === task.id) {
// Copy the task and update its name
return { ...task, name: newName };
}
// Return the original task if it's not the edited task
return task;
});
setTasks(editedTaskList);
}
```
Pass `editTask` into our `<Todo />` components as a prop in the same way we did with `deleteTask`:
```jsx
const taskList = tasks.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
toggleTaskCompleted={toggleTaskCompleted}
deleteTask={deleteTask}
editTask={editTask}
/>
));
```
Now open `Todo.jsx`. We're going to do some refactoring.
## A UI for editing
In order to allow users to edit a task, we have to provide a user interface for them to do so. First, import `useState` into the `<Todo />` component like we did before with the `<App />` component:
```jsx
import { useState } from "react";
```
We'll use this to set an `isEditing` state with a default value of `false`. Add the following line just inside the top of your `<Todo />` component definition:
```jsx
const [isEditing, setEditing] = useState(false);
```
Next, we're going to rethink the `<Todo />` component. From now on, we want it to display one of two possible "templates", rather than the single template it has used so far:
- The "view" template, when we are just viewing a todo; this is what we've used in the tutorial thus far.
- The "editing" template, when we are editing a todo. We're about to create this.
Copy this block of code into the `Todo()` function, beneath your `useState()` hook but above the `return` statement:
```jsx
const editingTemplate = (
<form className="stack-small">
<div className="form-group">
<label className="todo-label" htmlFor={props.id}>
New name for {props.name}
</label>
<input id={props.id} className="todo-text" type="text" />
</div>
<div className="btn-group">
<button type="button" className="btn todo-cancel">
Cancel
<span className="visually-hidden">renaming {props.name}</span>
</button>
<button type="submit" className="btn btn__primary todo-edit">
Save
<span className="visually-hidden">new name for {props.name}</span>
</button>
</div>
</form>
);
const viewTemplate = (
<div className="stack-small">
<div className="c-cb">
<input
id={props.id}
type="checkbox"
defaultChecked={props.completed}
onChange={() => props.toggleTaskCompleted(props.id)}
/>
<label className="todo-label" htmlFor={props.id}>
{props.name}
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">{props.name}</span>
</button>
<button
type="button"
className="btn btn__danger"
onClick={() => props.deleteTask(props.id)}>
Delete <span className="visually-hidden">{props.name}</span>
</button>
</div>
</div>
);
```
We've now got the two different template structures β "edit" and "view" β defined inside two separate constants. This means that the `return` statement of `<Todo />` is now repetitious β it also contains a definition of the "view" template. We can clean this up by using **conditional rendering** to determine which template the component returns, and is therefore rendered in the UI.
## Conditional rendering
In JSX, we can use a condition to change what is rendered by the browser. To write a condition in JSX, we can use a [ternary operator](/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator).
In the case of our `<Todo />` component, our condition is "Is this task being edited?" Change the `return` statement inside `Todo()` so that it reads like so:
```jsx
return <li className="todo">{isEditing ? editingTemplate : viewTemplate}</li>;
```
Your browser should render all your tasks just like before. To see the editing template, you will have to change the default `isEditing` state from `false` to `true` in your code for now; we will look at making the edit button toggle this in the next section!
## Toggling the `<Todo />` templates
At long last, we are ready to make our final core feature interactive. To start with, we want to call `setEditing()` with a value of `true` when a user presses the "Edit" button in our `viewTemplate`, so that we can switch templates.
Update the "Edit" button in the `viewTemplate` like so:
```jsx
<button type="button" className="btn" onClick={() => setEditing(true)}>
Edit <span className="visually-hidden">{props.name}</span>
</button>
```
Now we'll add the same `onClick` handler to the "Cancel" button in the `editingTemplate`, but this time we'll set `isEditing` to `false` so that it switches us back to the view template.
Update the "Cancel" button in the `editingTemplate` like so:
```jsx
<button
type="button"
className="btn todo-cancel"
onClick={() => setEditing(false)}>
Cancel
<span className="visually-hidden">renaming {props.name}</span>
</button>
```
With this code in place, you should be able to press the "Edit" and "Cancel" buttons in your todo items to toggle between templates.


The next step is to actually make the editing functionality work.
## Editing from the UI
Much of what we're about to do will mirror the work we did in `Form.jsx`: as the user types in our new input field, we need to track the text they enter; once they submit the form, we need to use a callback prop to update our state with the new name of the task.
We'll start by making a new hook for storing and setting the new name. Still in `Todo.jsx`, put the following underneath the existing hook:
```jsx
const [newName, setNewName] = useState("");
```
Next, create a `handleChange()` function that will set the new name; put this underneath the hooks but before the templates:
```jsx
function handleChange(e) {
setNewName(e.target.value);
}
```
Now we'll update our `editingTemplate`'s `<input />` field, setting a `value` attribute of `newName`, and binding our `handleChange()` function to its `onChange` event. Update it as follows:
```jsx
<input
id={props.id}
className="todo-text"
type="text"
value={newName}
onChange={handleChange}
/>
```
Finally, we need to create a function to handle the edit form's `onSubmit` event. Add the following just below `handleChange()`:
```jsx
function handleSubmit(e) {
e.preventDefault();
props.editTask(props.id, newName);
setNewName("");
setEditing(false);
}
```
Remember that our `editTask()` callback prop needs the ID of the task we're editing as well as its new name.
Bind this function to the form's `submit` event by adding the following `onSubmit` handler to the `editingTemplate`'s `<form>`:
```jsx
<form className="stack-small" onSubmit={handleSubmit}>
```
You should now be able to edit a task in your browser. At this point, your `Todo.jsx` file should look like this:
```jsx
function Todo(props) {
const [isEditing, setEditing] = useState(false);
const [newName, setNewName] = useState("");
function handleChange(e) {
setNewName(e.target.value);
}
function handleSubmit(e) {
e.preventDefault();
props.editTask(props.id, newName);
setNewName("");
setEditing(false);
}
const editingTemplate = (
<form className="stack-small" onSubmit={handleSubmit}>
<div className="form-group">
<label className="todo-label" htmlFor={props.id}>
New name for {props.name}
</label>
<input
id={props.id}
className="todo-text"
type="text"
value={newName}
onChange={handleChange}
/>
</div>
<div className="btn-group">
<button
type="button"
className="btn todo-cancel"
onClick={() => setEditing(false)}>
Cancel
<span className="visually-hidden">renaming {props.name}</span>
</button>
<button type="submit" className="btn btn__primary todo-edit">
Save
<span className="visually-hidden">new name for {props.name}</span>
</button>
</div>
</form>
);
const viewTemplate = (
<div className="stack-small">
<div className="c-cb">
<input
id={props.id}
type="checkbox"
defaultChecked={props.completed}
onChange={() => props.toggleTaskCompleted(props.id)}
/>
<label className="todo-label" htmlFor={props.id}>
{props.name}
</label>
</div>
<div className="btn-group">
<button
type="button"
className="btn"
onClick={() => {
setEditing(true);
}}>
Edit <span className="visually-hidden">{props.name}</span>
</button>
<button
type="button"
className="btn btn__danger"
onClick={() => props.deleteTask(props.id)}>
Delete <span className="visually-hidden">{props.name}</span>
</button>
</div>
</div>
);
return <li className="todo">{isEditing ? editingTemplate : viewTemplate}</li>;
}
export default Todo;
```
## Back to the filter buttons
Now that our main features are complete, we can think about our filter buttons. Currently, they repeat the "All" label, and they have no functionality! We will be reapplying some skills we used in our `<Todo />` component to:
- Create a hook for storing the active filter.
- Render an array of `<FilterButton />` elements that allow users to change the active filter between all, completed, and incomplete.
### Adding a filter hook
Add a new hook to your `App()` function that reads and sets a filter. We want the default filter to be `All` because all of our tasks should be shown initially:
```jsx
const [filter, setFilter] = useState("All");
```
### Defining our filters
Our goal right now is two-fold:
- Each filter should have a unique name.
- Each filter should have a unique behavior.
A JavaScript object would be a great way to relate names to behaviors: each key is the name of a filter; each property is the behavior associated with that name.
At the top of `App.jsx`, beneath our imports but above our `App()` function, let's add an object called `FILTER_MAP`:
```jsx
const FILTER_MAP = {
All: () => true,
Active: (task) => !task.completed,
Completed: (task) => task.completed,
};
```
The values of `FILTER_MAP` are functions that we will use to filter the `tasks` data array:
- The `All` filter shows all tasks, so we return `true` for all tasks.
- The `Active` filter shows tasks whose `completed` prop is `false`.
- The `Completed` filter shows tasks whose `completed` prop is `true`.
Beneath our previous addition, add the following β here we are using the [`Object.keys()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) method to collect an array of `FILTER_NAMES`:
```jsx
const FILTER_NAMES = Object.keys(FILTER_MAP);
```
> **Note:** We are defining these constants outside our `App()` function because if they were defined inside it, they would be recalculated every time the `<App />` component re-renders, and we don't want that. This information will never change no matter what our application does.
### Rendering the filters
Now that we have the `FILTER_NAMES` array, we can use it to render all three of our filters. Inside the `App()` function we can create a constant called `filterList`, which we will use to map over our array of names and return a `<FilterButton />` component. Remember, we need keys here, too.
Add the following underneath your `taskList` constant declaration:
```jsx
const filterList = FILTER_NAMES.map((name) => (
<FilterButton key={name} name={name} />
));
```
Now we'll replace the three repeated `<FilterButton />`s in `App.jsx` with this `filterList`. Replace the following:
```jsx
<FilterButton />
<FilterButton />
<FilterButton />
```
With this:
```jsx-nolint
{filterList}
```
This won't work yet. We've got a bit more work to do first.
### Interactive filters
To make our filter buttons interactive, we should consider what props they need to utilize.
- We know that the `<FilterButton />` should report whether it is currently pressed, and it should be pressed if its name matches the current value of our filter state.
- We know that the `<FilterButton />` needs a callback to set the active filter. We can make direct use of our `setFilter` hook.
Update your `filterList` constant as follows:
```jsx
const filterList = FILTER_NAMES.map((name) => (
<FilterButton
key={name}
name={name}
isPressed={name === filter}
setFilter={setFilter}
/>
));
```
In the same way as we did earlier with our `<Todo />` component, we now have to update `FilterButton.jsx` to utilize the props we have given it. Do each of the following, and remember to use curly braces to read these variables!
- Replace `all` with `{props.name}`.
- Set the value of `aria-pressed` to `{props.isPressed}`.
- Add an `onClick` handler that calls `props.setFilter()` with the filter's name.
With all of that done, your `FilterButton.jsx` file should read like this:
```jsx
function FilterButton(props) {
return (
<button
type="button"
className="btn toggle-btn"
aria-pressed={props.isPressed}
onClick={() => props.setFilter(props.name)}>
<span className="visually-hidden">Show </span>
<span>{props.name}</span>
<span className="visually-hidden"> tasks</span>
</button>
);
}
export default FilterButton;
```
Visit your browser again. You should see that the different buttons have been given their respective names. When you press a filter button, you should see its text take on a new outline β this tells you it has been selected. And if you look at your DevTool's Page Inspector while clicking the buttons, you'll see the `aria-pressed` attribute values change accordingly.

However, our buttons still don't actually filter the todos in the UI! Let's finish this off.
### Filtering tasks in the UI
Right now, our `taskList` constant in `App()` maps over the tasks state and returns a new `<Todo />` component for all of them. This is not what we want! A task should only render if it is included in the results of applying the selected filter. Before we map over the tasks state, we should filter it (with [`Array.prototype.filter()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)) to eliminate objects we don't want to render.
Update your `taskList` like so:
```jsx
const taskList = tasks
.filter(FILTER_MAP[filter])
.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
toggleTaskCompleted={toggleTaskCompleted}
deleteTask={deleteTask}
editTask={editTask}
/>
));
```
In order to decide which callback function to use in `Array.prototype.filter()`, we access the value in `FILTER_MAP` that corresponds to the key of our filter state. When filter is `All`, for example, `FILTER_MAP[filter]` will evaluate to `() => true`.
Choosing a filter in your browser will now remove the tasks that do not meet its criteria. The count in the heading above the list will also change to reflect the list!

## Summary
So that's it β our app is now functionally complete. However, now that we've implemented all of our features, we can make a few improvements to ensure that a wider range of users can use our app. Our next article rounds things off for our React tutorials by looking at including focus management in React, which can improve usability and reduce confusion for both keyboard-only and screen reader users.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/react_accessibility/index.md | ---
title: Accessibility in React
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_accessibility
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
In our final tutorial article, we'll focus on (pun intended) accessibility, including focus management in React, which can improve usability and reduce confusion for both keyboard-only and screen reader users.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn about implementing keyboard accessibility in React.</td>
</tr>
</tbody>
</table>
## Including keyboard users
At this point, we've implemented all the features we set out to implement. Users can add a new task, check and uncheck tasks, delete tasks, or edit task names. Also, they can filter their task list by all, active, or completed tasks.
Or, at least, they can do all of these things with a mouse. Unfortunately, these features are not very accessible to keyboard-only users. Let's explore this now.
## Exploring the keyboard usability problem
Start by clicking on the input at the top of our app, as if you're going to add a new task. You'll see a thick, dashed outline around that input. This outline is your visual indicator that the browser is currently focused on this element. Press the <kbd>Tab</kbd> key, and you will see the outline appear around the "Add" button beneath the input. This shows you that the browser's focus has moved.
Press <kbd>Tab</kbd> a few more times, and you will see this dashed focus indicator move between each of the filter buttons. Keep going until the focus indicator is around the first "Edit" button. Press <kbd>Enter</kbd>.
The `<Todo />` component will switch templates, as we designed, and you'll see a form that lets us edit the name of the task.
But where did our focus indicator go?
When we switch between templates in our `<Todo />` component, we completely remove the elements from the old template and replace them with the elements from the new template. That means the element that we were focused on no longer exists, so there's no visual cue as to where the browser's focus is. This could confuse a wide variety of users β particularly users who rely on the keyboard, or users who use assistive technology.
To improve the experience for keyboard and assistive technology users, we should manage the browser's focus ourselves.
### Aside: a note on our focus indicator
If you click the "All", "Active", or "Completed" filter buttons with your mouse, you _won't_ see a visible focus indicator, but you will do if you move between them with the <kbd>Tab</kbd> key on your keyboard. Don't worry β your code isn't broken!
Our CSS file uses the [`:focus-visible`](/en-US/docs/Web/CSS/:focus-visible) pseudo-class to provide custom styling for the focus indicator, and the browser uses a set of internal rules to determine when to show it to the user. Generally, the browser _will_ show a focus indicator in response to keyboard input, and _might_ show it in response to mouse input. `<button>` elements _don't_ show a focus indicator in response to mouse input, while `<input>` elements _do_.
The behavior of `:focus-visible` is more selective than the older [`:focus`](/en-US/docs/Web/CSS/:focus) pseudo-class, with which you might be more familiar. `:focus` shows a focus indicator in many more situations, and you can use it instead of or in combination with `:focus-visible` if you prefer.
## Focusing between templates
When a user changes the `<Todo />` template from viewing to editing, we should focus on the `<input>` used to rename it; when they change back from editing to viewing, we should move focus back to the "Edit" button.
### Targeting our elements
Up to this point, we've been writing JSX components and letting React build the resulting DOM behind the scenes. Most of the time, we don't need to target specific elements in the DOM because we can use React's state and props to control what gets rendered. To manage focus, however, we _do_ need to be able to target specific DOM elements.
This is where the `useRef()` hook comes in.
First, change the `import` statement at the top of `Todo.jsx` so that it includes `useRef`:
```jsx
import { useRef, useState } from "react";
```
`useRef()` creates an object with a single property: `current`. Refs can store any values we want them to, and we can look up those values later. We can even store references to DOM elements, which is exactly what we're going to do here.
Next, create two new constants beneath the `useState()` hooks in your `Todo()` function. Each should be a ref β one for the "Edit" button in the view template and one for the edit field in the editing template.
```jsx
const editFieldRef = useRef(null);
const editButtonRef = useRef(null);
```
These refs have a default value of `null` to make it clear that they'll be empty until they're attached to their DOM elements. To attach them to their elements, we'll add the special `ref` attribute to each element's JSX, and set the values of those attributes to the appropriately named `ref` objects.
Update the `<input>` in your editing template so that it reads like this:
```jsx
<input
id={props.id}
className="todo-text"
type="text"
value={newName}
onChange={handleChange}
ref={editFieldRef}
/>
```
Update the "Edit" button in your view template so that it reads like this:
```jsx
<button
type="button"
className="btn"
onClick={() => setEditing(true)}
ref={editButtonRef}>
Edit <span className="visually-hidden">{props.name}</span>
</button>
```
Doing this will populate our `editFieldRef` and `editButtonRef` with references to the DOM elements they're attached to, but _only_ after React has rendered the component. Test that out for yourself: add the following line somewhere in the body of your `Todo()` function, below where `editButtonRef` is initialized:
```jsx
console.log(editButtonRef.current);
```
You'll see that the value of `editButtonRef.current` is `null` when the component first renders, but if you click an "Edit" button, it will log the `<input>` element to the console. This is because the ref is populated only after the component renders, and clicking the "Edit" button causes the component to re-render. Be sure to delete this log before moving on.
> **Note:** Your logs will appear 6 times because we have 3 instances of `<Todo />` in our app and React renders our components twice in development.
We're getting closer! To take advantage of our newly referenced elements, we need to use another React hook: `useEffect()`.
### Implementing `useEffect()`
[`useEffect()`](https://react.dev/reference/react/useEffect) is so named because it runs any side-effects that we'd like to add to the render process but which can't be run inside the main function body. `useEffect()` runs right after a component renders, meaning the DOM elements we referenced in the previous section will be available for us to use.
Change the import statement of `Todo.jsx` again to add `useEffect`:
```jsx
import { useEffect, useRef, useState } from "react";
```
`useEffect()` takes a function as an argument; this function is executed _after_ the component renders. To demonstrate this, put the following `useEffect()` call just above the `return` statement in the body of `Todo()`, and pass a function into it that logs the words "side effect" to your console:
```jsx
useEffect(() => {
console.log("side effect");
});
```
To illustrate the difference between the main render process and code run inside `useEffect()`, add another log β put this one below the previous addition:
```jsx
console.log("main render");
```
Now, open the app in your browser. You should see both messages in your console, with each one repeating multiple times. Note how "main render" logged first, and "side effect" logged second, even though the "side effect" log appears first in the code.
```plain
main render Todo.jsx
side effect Todo.jsx
```
Again, the logs are ordered this way because code inside `useEffect()` runs _after_ the component renders. This takes some getting used to, just keep it in mind as you move forward. For now, delete `console.log("main render")` and we'll move on to implementing our focus management.
### Focusing on our editing field
Now that we know our `useEffect()` hook works, we can manage focus with it. As a reminder, we want to focus on the editing field when we switch to the editing template.
Update your existing `useEffect()` hook so that it reads like this:
```jsx
useEffect(() => {
if (isEditing) {
editFieldRef.current.focus();
}
}, [isEditing]);
```
These changes make it so that, if `isEditing` is true, React reads the current value of the `editFieldRef` and moves browser focus to it. We also pass an array into `useEffect()` as a second argument. This array is a list of values `useEffect()` should depend on. With these values included, `useEffect()` will only run when one of those values changes. We only want to change focus when the value of `isEditing` changes.
Try it now: use the <kbd>Tab</kbd> key to navigate to one of the "Edit" buttons, then press <kbd>Enter</kbd>. You should see the `<Todo />` component switch to its editing template, and the browser focus indicator should appear around the `<input>` element!
### Moving focus back to the edit button
At first glance, getting React to move focus back to our "Edit" button when the edit is saved or cancelled appears deceptively easy. Surely we could add a condition to our `useEffect` to focus on the edit button if `isEditing` is `false`? Let's try it now β update your `useEffect()` call like so:
```jsx
useEffect(() => {
if (isEditing) {
editFieldRef.current.focus();
} else {
editButtonRef.current.focus();
}
}, [isEditing]);
```
This kind of works. If you use your keyboard to trigger the "Edit" button (remember: <kbd>Tab</kbd> to it and press <kbd>Enter</kbd>), you'll see that your focus moves between the Edit `<input>` and "Edit" button as you start and end an edit. However, you may have noticed a new problem β the "Edit" button in the final `<Todo />` component is focused immediately on page load before we even interact with the app!
Our `useEffect()` hook is behaving exactly as we designed it: it runs as soon as the component renders, sees that `isEditing` is `false`, and focuses the "Edit" button. There are three instances of `<Todo />`, and focus is given to the "Edit" button of the one that renders last.
We need to refactor our approach so that focus changes only when `isEditing` changes from one value to another.
## More robust focus management
To meet our refined criteria, we need to know not just the value of `isEditing`, but also _when that value has changed_. To do that, we need to be able to read the previous value of the `isEditing` constant. Using pseudocode, our logic should be something like this:
```jsx
if (wasNotEditingBefore && isEditingNow) {
focusOnEditField();
} else if (wasEditingBefore && isNotEditingNow) {
focusOnEditButton();
}
```
The React team has discussed [ways to get a component's previous state](https://reactjs.org/docs/hooks-faq.html#how-to-get-the-previous-props-or-state), and provided an example hook we can use for the job.
### Enter `usePrevious()`
Paste the following code near the top of `Todo.jsx`, above your `Todo()` function.
```jsx
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
```
`usePrevious()` is a _custom hook_ that tracks a value across renders. It:
1. Uses the `useRef()` hook to create an empty `ref`.
2. Returns the `ref`'s `current` value to the component that called it.
3. Calls `useEffect()` and updates the value stored in `ref.current` after each rendering of the calling component.
The behavior of `useEffect()` is key to this functionality. Because `ref.current` is updated inside a `useEffect()` call, it's always one step behind whatever value is in the component's main render cycle β hence the name `usePrevious()`.
### Using `usePrevious()`
Now we can define a `wasEditing` constant to track the previous value of `isEditing`; this is achieved by calling `usePrevious` with `isEditing` as an argument. Add the following inside `Todo()`, below the `useRef` lines:
```jsx
const wasEditing = usePrevious(isEditing);
```
You can see how `usePrevious()` behaves by adding a console log beneath this line:
```jsx
console.log(wasEditing);
```
In this log, the `current` value of `wasEditing` will always be the previous value of `isEditing`. Click on the "Edit" and "Cancel" button a few times to watch it change, then delete this log when you're ready to move on.
With this `wasEditing` constant, we can update our `useEffect()` hook to implement the pseudocode we discussed before:
```jsx
useEffect(() => {
if (!wasEditing && isEditing) {
editFieldRef.current.focus();
} else if (wasEditing && !isEditing) {
editButtonRef.current.focus();
}
}, [wasEditing, isEditing]);
```
Note that the logic of `useEffect()` now depends on `wasEditing`, so we provide it in the array of dependencies.
Try using your keyboard to activate the "Edit" and "Cancel" buttons in the `<Todo />` component; you'll see the browser focus indicator move appropriately, without the problem we discussed at the start of this section.
## Focusing when the user deletes a task
There's one last keyboard experience gap: when a user deletes a task from the list, the focus vanishes. We're going to follow a pattern similar to our previous changes: we'll make a new ref, and utilize our `usePrevious()` hook, so that we can focus on the list heading whenever a user deletes a task.
### Why the list heading?
Sometimes, the place we want to send our focus to is obvious: when we toggled our `<Todo />` templates, we had an origin point to "go back" to β the "Edit" button. In this case however, since we're completely removing elements from the DOM, we have no place to go back to. The next best thing is an intuitive location somewhere nearby. The list heading is our best choice because it's close to the list item the user will delete, and focusing on it will tell the user how many tasks are left.
### Creating our ref
Import the `useRef()` and `useEffect()` hooks into `App.jsx` β you'll need them both below:
```jsx
import { useState, useRef, useEffect } from "react";
```
Next, declare a new ref inside the `App()` function, just above the `return` statement:
```jsx
const listHeadingRef = useRef(null);
```
### Prepare the heading
Heading elements like our `<h2>` are not usually focusable. This isn't a problem β we can make any element programmatically focusable by adding the attribute [`tabindex="-1"`](/en-US/docs/Web/HTML/Global_attributes/tabindex) to it. This means _only focusable with JavaScript_. You can't press <kbd>Tab</kbd> to focus on an element with a tabindex of `-1` the same way you could do with a [`<button>`](/en-US/docs/Web/HTML/Element/button) or [`<a>`](/en-US/docs/Web/HTML/Element/a) element (this can be done using `tabindex="0"`, but that's not appropriate in this case).
Let's add the `tabindex` attribute β written as `tabIndex` in JSX β to the heading above our list of tasks, along with our `listHeadingRef`:
```jsx
<h2 id="list-heading" tabIndex="-1" ref={listHeadingRef}>
{headingText}
</h2>
```
> **Note:** The `tabindex` attribute is excellent for accessibility edge cases, but you should take **great care** not to overuse it. Only apply a `tabindex` to an element when you're sure that making it focusable will benefit your user somehow. In most cases, you should utilize elements that can naturally take focus, such as buttons, anchors, and inputs. Irresponsible usage of `tabindex` could have a profoundly negative impact on keyboard and screen reader users!
### Getting previous state
We want to focus on the element associated with our ref (via the `ref` attribute) only when our user deletes a task from their list. That's going to require the `usePrevious()` hook we used earlier on. Add it to the top of your `App.jsx` file, just below the imports:
```jsx
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
```
Now add the following, above the `return` statement inside the `App()` function:
```jsx
const prevTaskLength = usePrevious(tasks.length);
```
Here we are invoking `usePrevious()` to track the previous length of the tasks array.
> **Note:** Since we're now utilizing `usePrevious()` in two files, it might be more efficient to move the `usePrevious()` function into its own file, export it from that file, and import it where you need it. Try doing this as an exercise once you've got to the end.
### Using `useEffect()` to control our heading focus
Now that we've stored how many tasks we previously had, we can set up a `useEffect()` hook to run when our number of tasks changes, which will focus the heading if the number of tasks we have now is less than it previously was β that is, we deleted a task!
Add the following into the body of your `App()` function, just below your previous additions:
```jsx
useEffect(() => {
if (tasks.length < prevTaskLength) {
listHeadingRef.current.focus();
}
}, [tasks.length, prevTaskLength]);
```
We only try to focus on our list heading if we have fewer tasks now than we did before. The dependencies passed into this hook ensure it will only try to re-run when either of those values (the number of current tasks, or the number of previous tasks) changes.
Now, when you use your keyboard to delete a task in your browser, you will see our dashed focus outline appear around the heading above the list.
## Finished!
You've just finished building a React app from the ground up! Congratulations! The skills you've learned here will be a great foundation to build on as you continue working with React.
Most of the time, you can be an effective contributor to a React project even if all you do is think carefully about components and their state and props. Remember to always write the best HTML you can.
`useRef()` and `useEffect()` are somewhat advanced features, and you should be proud of yourself for using them! Look out for opportunities to practice them more, because doing so will allow you to create inclusive experiences for users. Remember: our app would have been inaccessible to keyboard users without them!
> **Note:** If you need to check your code against our version, you can find a finished version of the sample React app code in our [todo-react repository](https://github.com/mdn/todo-react). For a running live version, see <https://mdn.github.io/todo-react>.
In the very last article we'll present you with a list of React resources that you can use to go further in your learning.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_resources", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/svelte_todo_list_beginning/index.md | ---
title: Starting our Svelte to-do list app
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_Todo_list_beginning
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Now that we have a basic understanding of how things work in Svelte, we can start building our example app: a to-do list. In this article we will first have a look at the desired functionality of our app, and then we'll create a `Todos.svelte` component and put static markup and styles in place, leaving everything ready to start developing our to-do list app features, which we'll go on to in subsequent articles.
We want our users to be able to browse, add and delete tasks, and also to mark them as complete. This will be the basic functionality that we'll be developing in this tutorial series, and we'll look at some more advanced concepts along the way too.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
You'll need a terminal with node + npm installed to compile and build
your app.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn how to create a Svelte component, render it inside another
component, pass data into it using props, and save its state.
</td>
</tr>
</tbody>
</table>
## Code along with us
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/02-starting-our-todo-app
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/02-starting-our-todo-app
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To code along with us using the REPL, start at
<https://svelte.dev/repl/b7b831ea3a354d3789cefbc31e2ca495?version=3.23.2>
## To-do list app features
This is what our to-do list app will look like once it's ready:

Using this UI our user will be able to:
- Browse their tasks
- Mark tasks as completed/pending without deleting them
- Remove tasks
- Add new tasks
- Filter tasks by status: all tasks, active tasks, or completed tasks
- Edit tasks
- Mark all tasks as active/completed
- Remove all completed tasks
## Building our first component
Let's create a `Todos.svelte` component. This will contain our list of to-dos.
1. Create a new folder β `src/components`.
> **Note:** You can put your components anywhere inside the `src` folder, but the `components` folder is a recognized convention to follow, allowing you to find your components easily.
2. Create a file named `src/components/Todos.svelte` with the following content:
```svelte
<h1>Svelte to-do list</h1>
```
3. Change the `title` element in `public/index.html` to contain the text _Svelte to-do list_:
```svelte
<title>Svelte to-do list</title>
```
4. Open `src/App.svelte` and replace its contents with the following:
```svelte
<script>
import Todos from "./components/Todos.svelte";
</script>
<Todos />
```
5. In development mode, Svelte will issue a warning in the browser console when specifying a prop that doesn't exist in the component; in this case we have a `name` prop being specified when we instantiate the `App` component inside `src/main.js`, which isn't used inside `App`. The console should currently give you a message along the lines of "\<App> was created with unknown prop 'name'". To get rid of this, remove the `name` prop from `src/main.js`; it should now look like so:
```js
import App from "./App.svelte";
const app = new App({
target: document.body,
});
export default app;
```
Now if you check your testing server URL you'll see our `Todos.svelte` component being rendered:

## Adding static markup
For the moment we will start with a static markup representation of our app, so you can see what it will look like. Copy and paste the following into our `Todos.svelte` component file, replacing the existing content:
```svelte
<!-- Todos.svelte -->
<div class="todoapp stack-large">
<!-- NewTodo -->
<form>
<h2 class="label-wrapper">
<label for="todo-0" class="label__lg"> What needs to be done? </label>
</h2>
<input type="text" id="todo-0" autocomplete="off" class="input input__lg" />
<button type="submit" disabled="" class="btn btn__primary btn__lg">
Add
</button>
</form>
<!-- Filter -->
<div class="filters btn-group stack-exception">
<button class="btn toggle-btn" aria-pressed="true">
<span class="visually-hidden">Show</span>
<span>All</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" aria-pressed="false">
<span class="visually-hidden">Show</span>
<span>Active</span>
<span class="visually-hidden">tasks</span>
</button>
<button class="btn toggle-btn" aria-pressed="false">
<span class="visually-hidden">Show</span>
<span>Completed</span>
<span class="visually-hidden">tasks</span>
</button>
</div>
<!-- TodosStatus -->
<h2 id="list-heading">2 out of 3 items completed</h2>
<!-- Todos -->
<ul role="list" class="todo-list stack-large" aria-labelledby="list-heading">
<!-- todo-1 (editing mode) -->
<li class="todo">
<div class="stack-small">
<form class="stack-small">
<div class="form-group">
<label for="todo-1" class="todo-label">
New name for 'Create a Svelte starter app'
</label>
<input
type="text"
id="todo-1"
autocomplete="off"
class="todo-text" />
</div>
<div class="btn-group">
<button class="btn todo-cancel" type="button">
Cancel
<span class="visually-hidden">renaming Create a Svelte starter app</span>
</button>
<button class="btn btn__primary todo-edit" type="submit">
Save
<span class="visually-hidden">new name for Create a Svelte starter app</span>
</button>
</div>
</form>
</div>
</li>
<!-- todo-2 -->
<li class="todo">
<div class="stack-small">
<div class="c-cb">
<input type="checkbox" id="todo-2" checked />
<label for="todo-2" class="todo-label">
Create your first component
</label>
</div>
<div class="btn-group">
<button type="button" class="btn">
Edit
<span class="visually-hidden">Create your first component</span>
</button>
<button type="button" class="btn btn__danger">
Delete
<span class="visually-hidden">Create your first component</span>
</button>
</div>
</div>
</li>
<!-- todo-3 -->
<li class="todo">
<div class="stack-small">
<div class="c-cb">
<input type="checkbox" id="todo-3" />
<label for="todo-3" class="todo-label">
Complete the rest of the tutorial
</label>
</div>
<div class="btn-group">
<button type="button" class="btn">
Edit
<span class="visually-hidden">Complete the rest of the tutorial</span>
</button>
<button type="button" class="btn btn__danger">
Delete
<span class="visually-hidden">Complete the rest of the tutorial</span>
</button>
</div>
</div>
</li>
</ul>
<hr />
<!-- MoreActions -->
<div class="btn-group">
<button type="button" class="btn btn__primary">Check all</button>
<button type="button" class="btn btn__primary">Remove completed</button>
</div>
</div>
```
Check the rendered out again, and you'll see something like this:

The HTML markup above is not very nicely styled and it's also functionally useless. Nevertheless, let's have a look at the markup and see how it relates to our desired features:
- A label and a text box for entering new tasks
- Three buttons to filter by task status
- A label showing the total number of tasks and the completed tasks
- An unordered list, which holds a list item for each task
- When the task is being edited, the list item has an input and two button to cancel or save modifications
- If the task is not being edited, there's a checkbox to set the completed status, and two buttons to edit or delete the task
- Finally there are two buttons to check/uncheck all task and to remove completed tasks
In subsequent articles we'll get all these features working, and more besides.
### Accessibility features of the to-do list
You may notice some unusual attributes here. For example:
```svelte
<button class="btn toggle-btn" aria-pressed="true">
<span class="visually-hidden">Show</span>
<span>All</span>
<span class="visually-hidden">tasks</span>
</button>
```
Here, `aria-pressed` tells assistive technology (like screen readers) that the button can be in one of two states: `pressed` or `unpressed`. Think of these as analogs for on and off. Setting a value of `true` means that the button is pressed by default.
The class `visually-hidden` has no effect yet, because we have not included any CSS. Once we have put our styles in place, though, any element with this class will be hidden from sighted users and still available to screen reader users β this is because these words are not needed by sighted users; they are there to provide more information about what the button does for screen reader users that do not have the extra visual context to help them.
Further down, you can find the following `<ul>` element:
```svelte
<ul
role="list"
class="todo-list stack-large"
aria-labelledby="list-heading">
```
The `role` attribute helps assistive technology explain what kind of semantic value an element has β or what its purpose is. A `<ul>` is treated like a list by default, but the styles we're about to add will break that functionality. This role will restore the "list" meaning to the `<ul>` element. If you want to learn more about why this is necessary, you can check out Scott O'Hara's article ["Fixing Lists"](https://www.scottohara.me/blog/2019/01/12/lists-and-safari.html) (2019).
The `aria-labelledby` attribute tells assistive technologies that we're treating our `<h2>` with an `id` of `list-heading` as the label that describes the purpose of the list beneath it. Making this association gives the list a more informative context, which could help screen reader users better understand the purpose of it.
This seems like a good time to talk about how Svelte deals with accessibility; let's do that now.
## Svelte accessibility support
Svelte has a special emphasis on accessibility. The intention is to encourage developers to write more accessible code "by default". Being a compiler, Svelte can statically analyze our HTML templates to provide accessibility warnings when components are being compiled.
Accessibility (shortened to a11y) isn't always easy to get right, but Svelte will help by warning you if you write inaccessible markup.
For example, if we add an `<img>` element to our `todos.svelte` component without its corresponding `alt` prop:
```svelte
<h1>Svelte To-Do list</h1>
<img height="32" width="88" src="https://www.w3.org/WAI/wcag2A" />
```
The compiler will issue the following warning:
```bash
(!) Plugin svelte: A11y: <img> element should have an alt attribute
src/components/Todos.svelte
1: <h1>Svelte To-Do list</h1>
2:
3: <img height="32" width="88" src="https://www.w3.org/WAI/wcag2A">
^
created public/build/bundle.js in 220ms
[2020-07-15 04:07:43] waiting for changes...
```
Moreover, our editor can display this warning even before calling the compiler:

You can tell Svelte to ignore this warning for the next block of markup with a [comment](https://svelte.dev/docs/basic-markup#comments) beginning with `svelte-ignore`, like this:
```svelte
<!-- svelte-ignore a11y-missing-attribute -->
<img height="32" width="88" src="https://www.w3.org/WAI/wcag2A" />
```
> **Note:** With VSCode you can automatically add this ignore comment by clicking on the _Quick fixβ¦_ link or pressing <kbd>Ctrl</kbd> + <kbd>.</kbd>.
If you want to globally disable this warning, you can add this `onwarn` handler to your `rollup.config.js` file inside the configuration for the `Svelte` plugin, like this:
```js
plugins: [
svelte({
dev: !production,
css: (css) => {
css.write("public/build/bundle.css");
},
// Warnings are normally passed straight to Rollup. You can
// optionally handle them here, for example to squelch
// warnings with a particular code
onwarn: (warning, handler) => {
// e.g. I don't care about screen readers -> please DON'T DO THIS!!!
if (warning.code === "a11y-missing-attribute") {
return;
}
// let Rollup handle all other warnings normally
handler(warning);
},
}),
// β¦
];
```
By design, these warnings are implemented in the compiler itself, and not as a plug-in that you may choose to add to your project. The idea is to check for a11y issues in your markup by default and let you opt out of specific warnings.
> **Note:** You should only disable these warnings if you have good reasons to do so, for example while building a quick prototype. It's important to be a good web citizen and make your pages accessible to the broadest possible userbase.
The accessibility rules checked by Svelte are taken from [eslint-plugin-jsx-a11y](https://github.com/jsx-eslint/eslint-plugin-jsx-a11y#supported-rules), a plugin for ESLint that provides static checks for many accessibility rules on JSX elements. Svelte aims to implement all of them in its compiler, and most of them have already been ported to Svelte. On GitHub you can see [which accessibility checks are still missing](https://github.com/sveltejs/svelte/issues/820). You can check the meaning of each rule by clicking on its link.
## Styling our markup
Let's make the to-do list look a little better. Replace the contents of the file `public/global.css` with the following:
```css
/* RESETS */
*,
*::before,
*::after {
box-sizing: border-box;
}
*:focus {
outline: 3px dashed #228bec;
outline-offset: 0;
}
html {
font: 62.5% / 1.15 sans-serif;
}
h1,
h2 {
margin-bottom: 0;
}
ul {
list-style: none;
padding: 0;
}
button {
border: none;
margin: 0;
padding: 0;
width: auto;
overflow: visible;
background: transparent;
color: inherit;
font: inherit;
line-height: normal;
-webkit-font-smoothing: inherit;
-moz-osx-font-smoothing: inherit;
appearance: none;
}
button::-moz-focus-inner {
border: 0;
}
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
font-size: 100%;
line-height: 1.15;
margin: 0;
}
button,
input {
overflow: visible;
}
input[type="text"] {
border-radius: 0;
}
body {
width: 100%;
max-width: 68rem;
margin: 0 auto;
font:
1.6rem/1.25 Arial,
sans-serif;
background-color: #f5f5f5;
color: #4d4d4d;
}
@media screen and (min-width: 620px) {
body {
font-size: 1.9rem;
line-height: 1.31579;
}
}
/*END RESETS*/
/* GLOBAL STYLES */
.form-group > input[type="text"] {
display: inline-block;
margin-top: 0.4rem;
}
.btn {
padding: 0.8rem 1rem 0.7rem;
border: 0.2rem solid #4d4d4d;
cursor: pointer;
text-transform: capitalize;
}
.btn.toggle-btn {
border-width: 1px;
border-color: #d3d3d3;
}
.btn.toggle-btn[aria-pressed="true"] {
text-decoration: underline;
border-color: #4d4d4d;
}
.btn__danger {
color: #fff;
background-color: #ca3c3c;
border-color: #bd2130;
}
.btn__filter {
border-color: lightgrey;
}
.btn__primary {
color: #fff;
background-color: #000;
}
.btn__primary:disabled {
color: darkgrey;
background-color: #565656;
}
.btn-group {
display: flex;
justify-content: space-between;
}
.btn-group > * {
flex: 1 1 49%;
}
.btn-group > * + * {
margin-left: 0.8rem;
}
.label-wrapper {
margin: 0;
flex: 0 0 100%;
text-align: center;
}
.visually-hidden {
position: absolute !important;
height: 1px;
width: 1px;
overflow: hidden;
clip: rect(1px 1px 1px 1px);
clip: rect(1px, 1px, 1px, 1px);
white-space: nowrap;
}
[class*="stack"] > * {
margin-top: 0;
margin-bottom: 0;
}
.stack-small > * + * {
margin-top: 1.25rem;
}
.stack-large > * + * {
margin-top: 2.5rem;
}
@media screen and (min-width: 550px) {
.stack-small > * + * {
margin-top: 1.4rem;
}
.stack-large > * + * {
margin-top: 2.8rem;
}
}
.stack-exception {
margin-top: 1.2rem;
}
/* END GLOBAL STYLES */
.todoapp {
background: #fff;
margin: 2rem 0 4rem 0;
padding: 1rem;
position: relative;
box-shadow:
0 2px 4px 0 rgb(0 0 0 / 20%),
0 2.5rem 5rem 0 rgb(0 0 0 / 10%);
}
@media screen and (min-width: 550px) {
.todoapp {
padding: 4rem;
}
}
.todoapp > * {
max-width: 50rem;
margin-left: auto;
margin-right: auto;
}
.todoapp > form {
max-width: 100%;
}
.todoapp > h1 {
display: block;
max-width: 100%;
text-align: center;
margin: 0;
margin-bottom: 1rem;
}
.label__lg {
line-height: 1.01567;
font-weight: 300;
padding: 0.8rem;
margin-bottom: 1rem;
text-align: center;
}
.input__lg {
padding: 2rem;
border: 2px solid #000;
}
.input__lg:focus {
border-color: #4d4d4d;
box-shadow: inset 0 0 0 2px;
}
[class*="__lg"] {
display: inline-block;
width: 100%;
font-size: 1.9rem;
}
[class*="__lg"]:not(:last-child) {
margin-bottom: 1rem;
}
@media screen and (min-width: 620px) {
[class*="__lg"] {
font-size: 2.4rem;
}
}
.filters {
width: 100%;
margin: unset auto;
}
/* Todo item styles */
.todo {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
.todo > * {
flex: 0 0 100%;
}
.todo-text {
width: 100%;
min-height: 4.4rem;
padding: 0.4rem 0.8rem;
border: 2px solid #565656;
}
.todo-text:focus {
box-shadow: inset 0 0 0 2px;
}
/* CHECKBOX STYLES */
.c-cb {
box-sizing: border-box;
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
font-weight: 400;
font-size: 1.6rem;
line-height: 1.25;
display: block;
position: relative;
min-height: 44px;
padding-left: 40px;
clear: left;
}
.c-cb > label::before,
.c-cb > input[type="checkbox"] {
box-sizing: border-box;
top: -2px;
left: -2px;
width: 44px;
height: 44px;
}
.c-cb > input[type="checkbox"] {
-webkit-font-smoothing: antialiased;
cursor: pointer;
position: absolute;
z-index: 1;
margin: 0;
opacity: 0;
}
.c-cb > label {
font-size: inherit;
font-family: inherit;
line-height: inherit;
display: inline-block;
margin-bottom: 0;
padding: 8px 15px 5px;
cursor: pointer;
touch-action: manipulation;
}
.c-cb > label::before {
content: "";
position: absolute;
border: 2px solid currentcolor;
background: transparent;
}
.c-cb > input[type="checkbox"]:focus + label::before {
border-width: 4px;
outline: 3px dashed #228bec;
}
.c-cb > label::after {
box-sizing: content-box;
content: "";
position: absolute;
top: 11px;
left: 9px;
width: 18px;
height: 7px;
transform: rotate(-45deg);
border: solid;
border-width: 0 0 5px 5px;
border-top-color: transparent;
opacity: 0;
background: transparent;
}
.c-cb > input[type="checkbox"]:checked + label::after {
opacity: 1;
}
```
With our markup styled, everything now looks better:

## The code so far
### Git
To see the state of the code as it should be at the end of this article, access your copy of our repo like this:
```bash
cd mdn-svelte-tutorial/03-adding-dynamic-behavior
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/03-adding-dynamic-behavior
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To see the current state of the code in a REPL, visit:
<https://svelte.dev/repl/c862d964d48d473ca63ab91709a0a5a0?version=3.23.2>
## Summary
With our markup and styling in place, our to-do list app is starting to take shape, and we have everything ready so that we can start to focus on the features we have to implement.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_variables_props", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/vue_first_component/index.md | ---
title: Creating our first Vue component
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_first_component
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Now it's time to dive deeper into Vue, and create our own custom component β we'll start by creating a component to represent each item in the todo list. Along the way, we'll learn about a few important concepts such as calling components inside other components, passing data to them via props, and saving data state.
> **Note:** If you need to check your code against our version, you can find a finished version of the sample Vue app code in our [todo-vue repository](https://github.com/mdn/todo-vue). For a running live version, see <https://mdn.github.io/todo-vue/>.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with
<a
href="https://nodejs.org/en/download/"
rel="noopener noreferrer"
target="_blank"
>Node</a
>
and
<a
href="https://www.npmjs.com/get-npm"
rel="noopener noreferrer"
target="_blank"
>npm</a
>
installed.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn how to create a Vue component, render it inside another
component, pass data into it using props, and save its state.
</td>
</tr>
</tbody>
</table>
## Creating a ToDoItem component
Let's create our first component, which will display a single todo item. We'll use this to build our list of todos.
1. In your `moz-todo-vue/src/components` directory, create a new file named `ToDoItem.vue`. Open the file in your code editor.
2. Create the component's template section by adding `<template></template>` to the top of the file.
3. Create a `<script></script>` section below your template section. Inside the `<script>` tags, add a default exported object `export default {}`, which is your component object.
Your file should now look like this:
```vue
<template></template>
<script>
export default {};
</script>
```
We can now begin to add actual content to our `ToDoItem`. Vue templates are currently only allowed a single root element β one element needs to wrap everything inside the template section (this will change when Vue 3 comes out). We'll use a [`<div>`](/en-US/docs/Web/HTML/Element/div) for that root element.
1. Add an empty `<div>` inside your component template now.
2. Inside that `<div>`, let's add a checkbox and a corresponding label. Add an `id` to the checkbox, and a `for` attribute mapping the checkbox to the label, as shown below.
```vue
<template>
<div>
<input type="checkbox" id="todo-item" />
<label for="todo-item">My Todo Item</label>
</div>
</template>
```
### Using TodoItem inside our app
This is all fine, but we haven't added the component to our app yet, so there's no way to test it and see if everything is working. Let's add it now.
1. Open up `App.vue` again.
2. At the top of your `<script>` tag, add the following to import your `ToDoItem` component:
```js
import ToDoItem from "./components/ToDoItem.vue";
```
3. Inside your component object, add the `components` property, and inside it add your `ToDoItem` component to register it.
Your `<script>` contents should now look like this:
```js
import ToDoItem from "./components/ToDoItem.vue";
export default {
name: "app",
components: {
ToDoItem,
},
};
```
This is the same way that the `HelloWorld` component was registered by the Vue CLI earlier.
To actually render the `ToDoItem` component in the app, you need to go up into your `<template>` element and call it as a `<to-do-item></to-do-item>` element. Note that the component file name and its representation in JavaScript is in PascalCase (e.g. `ToDoList`), and the equivalent custom element is in {{Glossary("kebab_case", "kebab-case")}} (e.g. `<to-do-list>`).
It's necessary to use this casing style if you're writing Vue templates [in the DOM directly](https://vuejs.org/guide/essentials/component-basics.html#dom-template-parsing-caveats)
1. Underneath the [`<h1>`](/en-US/docs/Web/HTML/Element/Heading_Elements), create an unordered list ([`<ul>`](/en-US/docs/Web/HTML/Element/ul)) containing a single list item ([`<li>`](/en-US/docs/Web/HTML/Element/li)).
2. Inside the list item add `<to-do-item></to-do-item>`.
The `<template>` section of your `App.vue` file should now look something like this:
```vue
<div id="app">
<h1>To-Do List</h1>
<ul>
<li>
<to-do-item></to-do-item>
</li>
</ul>
</div>
```
If you check your rendered app again, you should now see your rendered `ToDoItem`, consisting of a checkbox and a label.

## Making components dynamic with props
Our `ToDoItem` component is still not very useful because we can only really include this once on a page (IDs need to be unique), and we have no way to set the label text. Nothing about this is dynamic.
What we need is some component state. This can be achieved by adding props to our component. You can think of props as being similar to inputs in a function. The value of a prop gives components an initial state that affects their display.
### Registering props
In Vue, there are two ways to register props:
- The first way is to just list props out as an array of strings. Each entry in the array corresponds to the name of a prop.
- The second way is to define props as an object, with each key corresponding to the prop name. Listing props as an object allows you to specify default values, mark props as required, perform basic object typing (specifically around JavaScript primitive types), and perform simple prop validation.
> **Note:** Prop validation only happens in development mode, so you can't strictly rely on it in production. Additionally, prop validation functions are invoked before the component instance is created, so they do not have access to the component state (or other props).
For this component, we'll use the object registration method.
1. Go back to your `ToDoItem.vue` file.
2. Add a `props` property inside the export `default {}` object, which contains an empty object.
3. Inside this object, add two properties with the keys `label` and `done`.
4. The `label` key's value should be an object with 2 properties (or **props**, as they are called in the context of being available to the components).
1. The first is a `required` property, which will have a value of `true`. This will tell Vue that we expect every instance of this component to have a label field. Vue will warn us if a `ToDoItem` component does not have a label field.
2. The second property we'll add is a `type` property. Set the value for this property as the JavaScript `String` type (note the capital "S"). This tells Vue that we expect the value of this property to be a string.
5. Now on to the `done` prop.
1. First add a `default` field, with a value of `false`. This means that when no `done` prop is passed to a `ToDoItem` component, the `done` prop will have a value of false (bear in mind that this is not required β we only need `default` on non-required props).
2. Next add a `type` field with a value of `Boolean`. This tells Vue we expect the value prop to be a JavaScript boolean type.
Your component object should now look like this:
```js
export default {
props: {
label: { required: true, type: String },
done: { default: false, type: Boolean },
},
};
```
### Using registered props
With these props defined inside the component object, we can now use these variable values inside our template. Let's start by adding the `label` prop to the component template.
In your `<template>`, replace the contents of the `<label>` element with `\{{label}}`.
`\{{}}` is a special template syntax in Vue, which lets us print the result of JavaScript expressions defined in our class, inside our template, including values and methods. It's important to know that content inside `\{{}}` is displayed as text and not HTML. In this case, we're printing the value of the `label` prop.
Your component's template section should now look like this:
```vue
<template>
<div>
<input type="checkbox" id="todo-item" />
<label for="todo-item">\{{ label }}</label>
</div>
</template>
```
Go back to your browser and you'll see the todo item rendered as before, but without a label (oh no!). Go to your browser's DevTools and you'll see a warning along these lines in the console:
```plain
[Vue warn]: Missing required prop: "label"
found in
---> <ToDoItem> at src/components/ToDoItem.vue
<App> at src/App.vue
<Root>
```
This is because we marked the `label` as a required prop, but we never gave the component that prop β we've defined where inside the template we want it used, but we haven't passed it into the component when calling it. Let's fix that.
Inside your `App.vue` file, add a `label` prop to the `<to-do-item></to-do-item>` component, just like a regular HTML attribute:
```vue
<to-do-item label="My ToDo Item"></to-do-item>
```
Now you'll see the label in your app, and the warning won't be spat out in the console again.
So that's props in a nutshell. Next we'll move on to how Vue persists data state.
## Vue's data object
If you change the value of the `label` prop passed into the `<to-do-item></to-do-item>` call in your `App` component, you should see it update. This is great. We have a checkbox, with an updatable label. However, we're currently not doing anything with the "done" prop β we can check the checkboxes in the UI, but nowhere in the app are we recording whether a todo item is actually done.
To achieve this, we want to bind the component's `done` prop to the `checked` attribute on the [`<input>`](/en-US/docs/Web/HTML/Element/input) element, so that it can serve as a record of whether the checkbox is checked or not. However, it's important that props serve as one-way data binding β a component should never alter the value of its own props. There are a lot of reasons for this. In part, components editing props can make debugging a challenge. If a value is passed to multiple children, it could be hard to track where the changes to that value were coming from. In addition, changing props can cause components to re-render. So mutating props in a component would trigger the component to rerender, which may in-turn trigger the mutation again.
To work around this, we can manage the `done` state using Vue's `data` property. The `data` property is where you can manage local state in a component, it lives inside the component object alongside the `props` property and has the following structure:
```js
data() {
return {
key: value
}
}
```
You'll note that the `data` property is a function. This is to keep the data values unique for each instance of a component at runtime β the function is invoked separately for each component instance. If you declared data as just an object, all instances of that component would share the same values. This is a side-effect of the way Vue registers components and something you do not want.
You use `this` to access a component's props and other properties from inside data, as you may expect. We'll see an example of this shortly.
> **Note:** Because of the way that `this` works in arrow functions (binding to the parent's context), you wouldn't be able to access any of the necessary attributes from inside `data` if you used an arrow function. So don't use an arrow function for the `data` property.
So let's add a `data` property to our `ToDoItem` component. This will return an object containing a single property that we'll call `isDone`, whose value is `this.done`.
Update the component object like so:
```js
export default {
props: {
label: { required: true, type: String },
done: { default: false, type: Boolean },
},
data() {
return {
isDone: this.done,
};
},
};
```
Vue does a little magic here β it binds all of your props directly to the component instance, so we don't have to call `this.props.done`. It also binds other attributes (`data`, which you've already seen, and others like `methods`, `computed`, etc.) directly to the instance. This is, in part, to make them available to your template. The down-side to this is that you need to keep the keys unique across these attributes. This is why we called our `data` attribute `isDone` instead of `done`.
So now we need to attach the `isDone` property to our component. In a similar fashion to how Vue uses `\{{}}` expressions to display JavaScript expressions inside templates, Vue has a special syntax to bind JavaScript expressions to HTML elements and components: **`v-bind`**. The `v-bind` expression looks like this:
```plain
v-bind:attribute="expression"
```
In other words, you prefix whatever attribute/prop you want to bind to with `v-bind:`. In most cases, you can use a shorthand for the `v-bind` property, which is to just prefix the attribute/prop with a colon. So `:attribute="expression"` works the same as `v-bind:attribute="expression"`.
So in the case of the checkbox in our `ToDoItem` component, we can use `v-bind` to map the `isDone` property to the `checked` attribute on the `<input>` element. Both of the following are equivalent:
```vue
<input type="checkbox" id="todo-item" v-bind:checked="isDone" />
<input type="checkbox" id="todo-item" :checked="isDone" />
```
You're free to use whichever pattern you would like. It's best to keep it consistent though. Because the shorthand syntax is more commonly used, this tutorial will stick to that pattern.
So let's do this. Update your `<input>` element now to include `:checked="isDone"`.
Test out your component by passing `:done="true"` to the `ToDoItem` call in `App.vue`. Note that you need to use the `v-bind` syntax, because otherwise `true` is passed as a string. The displayed checkbox should be checked.
```vue
<template>
<div id="app">
<h1>My To-Do List</h1>
<ul>
<li>
<to-do-item label="My ToDo Item" :done="true"></to-do-item>
</li>
</ul>
</div>
</template>
```
Try changing `true` to `false` and back again, reloading your app in between to see how the state changes.
## Giving Todos a unique id
Great! We now have a working checkbox where we can set the state programmatically. However, we can currently only add one `ToDoList` component to the page because the `id` is hardcoded. This would result in errors with assistive technology since the `id` is needed to correctly map labels to their checkboxes. To fix this, we can programmatically set the `id` in the component data.
We can use the [lodash](https://www.npmjs.com/package/lodash) package's `uniqueid()` method to help keep the index unique. This package exports a function that takes in a string and appends a unique integer to the end of the prefix. This will be sufficient for keeping component `id`s unique.
Let's add the package to our project with npm; stop your server and enter the following command into your terminal:
```bash
npm install --save lodash.uniqueid
```
> **Note:** If you prefer yarn, you could instead use `yarn add lodash.uniqueid`.
We can now import this package into our `ToDoItem` component. Add the following line at the top of `ToDoItem.vue`'s `<script>` element:
```js
import uniqueId from "lodash.uniqueid";
```
Next, add an `id` field to our data property, so the component object ends up looking like so (`uniqueId()` returns the specified prefix β `todo-` β with a unique string appended to it):
```js
import uniqueId from "lodash.uniqueid";
export default {
props: {
label: { required: true, type: String },
done: { default: false, type: Boolean },
},
data() {
return {
isDone: this.done,
id: uniqueId("todo-"),
};
},
};
```
Next, bind the `id` to both our checkbox's `id` attribute and the label's `for` attribute, updating the existing `id` and `for` attributes as shown:
```vue
<template>
<div>
<input type="checkbox" :id="id" :checked="isDone" />
<label :for="id">\{{ label }}</label>
</div>
</template>
```
## Summary
And that will do for this article. At this point we have a nicely-working `ToDoItem` component that can be passed a label to display, will store its checked state, and will be rendered with a unique `id` each time it is called. You can check if the unique `id`s are working by temporarily adding more `<to-do-item></to-do-item>` calls into `App.vue`, and then checking their rendered output with your browser's DevTools.
Now we're ready to add multiple `ToDoItem` components to our app. In our next article we'll look at adding a set of todo item data to our `App.vue` component, which we'll then loop through and display inside `ToDoItem` components using the `v-for` directive.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/react_interactivity_events_state/index.md | ---
title: "React interactivity: Events and state"
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_events_state
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
With our component plan worked out, it's now time to start updating our app from a completely static UI to one that actually allows us to interact and change things. In this article we'll do this, digging into events and state along the way, and ending up with an app in which we can successfully add and delete tasks, and toggle tasks as completed.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn about handling events and state in React, and use those to
start making the case study app interactive.
</td>
</tr>
</tbody>
</table>
## Handling events
If you've only written vanilla JavaScript before now, you might be used to having a separate JavaScript file in which you query for some DOM nodes and attach listeners to them. For example, an HTML file might have a button in it, like this:
```html
<button type="button">Say hi!</button>
```
And a JavaScript file might have some code like this:
```js
const btn = document.querySelector("button");
btn.addEventListener("click", () => {
alert("hi!");
});
```
In JSX, the code that describes the UI lives right alongside our event listeners:
```jsx
<button type="button" onClick={() => alert("hi!")}>
Say hi!
</button>
```
In this example, we're adding an `onClick` attribute to the {{htmlelement("button")}} element. The value of that attribute is a function that triggers a simple alert. This may seem counter to best practice advice about not writing event listeners in HTML, but remember: JSX is not HTML.
The `onClick` attribute has special meaning here: it tells React to run a given function when the user clicks on the button. There are a couple of other things to note:
- The {{Glossary("camel_case", "camel-cased")}} nature of `onClick` is important β JSX will not recognize `onclick` (again, it is already used in JavaScript for a specific purpose, which is related but different β standard [`onclick`](/en-US/docs/Web/API/Element/click_event) handler properties).
- All browser events follow this format in JSX β `on`, followed by the name of the event.
Let's apply this to our app, starting in the `Form.jsx` component.
### Handling form submission
At the top of the `Form()` component function (i.e., just below the `function Form() {` line), create a function named `handleSubmit()`. This function should [prevent the default behavior of the `submit` event](/en-US/docs/Learn/JavaScript/Building_blocks/Events#preventing_default_behavior). After that, it should trigger an `alert()`, which can say whatever you'd like. It should end up looking something like this:
```jsx
function handleSubmit(event) {
event.preventDefault();
alert("Hello, world!");
}
```
To use this function, add an `onSubmit` attribute to the [`<form>`](/en-US/docs/Web/HTML/Element/form) element, and set its value to the `handleSubmit` function:
```jsx
<form onSubmit={handleSubmit}>
```
Now if you head back to your browser and click on the "Add" button, your browser will show you an alert dialog with the words "Hello, world!" β or whatever you chose to write there.
## Callback props
In React applications, interactivity is rarely confined to just one component: events that happen in one component will affect other parts of the app. When we start giving ourselves the power to make new tasks, things that happen in the `<Form />` component will affect the list rendered in `<App />`.
We want our `handleSubmit()` function to ultimately help us create a new task, so we need a way to pass information from `<Form />` to `<App />`. We can't pass data from child to parent in the same way as we pass data from parent to child using standard props. Instead, we can write a function in `<App />` that will expect some data from our form as an input, then pass that function to `<Form />` as a prop. This function-as-a-prop is called a **callback prop**. Once we have our callback prop, we can call it inside `<Form />` to send the right data to `<App />`.
### Handling form submission via callbacks
Inside the `App()` function in `App.jsx`, create a function named `addTask()` which has a single parameter of `name`:
```jsx
function addTask(name) {
alert(name);
}
```
Next, pass `addTask()` into `<Form />` as a prop. The prop can have whatever name you want, but pick a name you'll understand later. Something like `addTask` works, because it matches the name of the function as well as what the function will do. Your `<Form />` component call should be updated as follows:
```jsx
<Form addTask={addTask} />
```
To use this prop, we must change the signature of the `Form()` function in `Form.jsx` so that it accepts `props` as a parameter:
```jsx
function Form(props) {
// ...
}
```
Finally, we can use this prop inside the `handleSubmit()` function in your `<Form />` component! Update it as follows:
```jsx
function handleSubmit(event) {
event.preventDefault();
props.addTask("Say hello!");
}
```
Clicking on the "Add" button in your browser will prove that the `addTask()` callback function works, but it'd be nice if we could get the alert to show us what we're typing in our input field! This is what we'll do next.
### Aside: a note on naming conventions
We passed the `addTask()` function into the `<Form />` component as the prop `addTask` so that the relationship between the `addTask()` _function_ and the `addTask` _prop_ would remain as clear as possible. Keep in mind, though, that prop names do not _need_ to be anything in particular. We could have passed `addTask()` into `<Form />` under any other name, such as this:
```diff
- <Form addTask={addTask} />
+ <Form onSubmit={addTask} />
```
This would make the `addTask()` function available to the `<Form />` component as the prop `onSubmit`. That prop could be used in `App.jsx` like this:
```diff
function handleSubmit(event) {
event.preventDefault();
- props.addTask("Say hello!");
+ props.onSubmit("Say hello!");
}
```
Here, the `on` prefix tells us that the prop is a callback function; `Submit` is our clue that a submit event will trigger this function.
While callback props often match the names of familiar event handlers, like `onSubmit` or `onClick`, they can be named just about anything that helps make their meaning clear. A hypothetical `<Menu />` component might include a callback function that runs when the menu is opened, as well as a separate callback function that runs when it's closed:
```jsx
<Menu onOpen={() => console.log("Hi!")} onClose={() => console.log("Bye!")} />
```
This `on*` naming convention is very common in the React ecosystem, so keep it in mind as you continue your learning. For the sake of clarity, we're going to stick with `addTask` and similar prop names for the rest of this tutorial. If you changed any prop names while reading this section, be sure to change them back before continuing!
## Persisting and changing data with state
So far, we've used props to pass data through our components and this has served us just fine. Now that we're dealing with interactivity, however, we need the ability to create new data, retain it, and update it later. Props are not the right tool for this job because they are immutable β a component cannot change or create its own props.
This is where **state** comes in. If we think of props as a way to communicate between components, we can think of state as a way to give components "memory" β information they can hold onto and update as needed.
React provides a special function for introducing state to a component, aptly named `useState()`.
> **Note:** `useState()` is part of a special category of functions called **hooks**, each of which can be used to add new functionality to a component. We'll learn about other hooks later on.
To use `useState()`, we need to import it from the React module. Add the following line to the top of your `Form.jsx` file, above the `Form()` function definition:
```jsx
import { useState } from "react";
```
`useState()` takes a single argument that determines the initial value of the state. This argument can be a string, a number, an array, an object, or any other JavaScript data type. `useState()` returns an array containing two items. The first item is the current value of the state; the second item is a function that can be used to update the state.
Let's create a `name` state. Write the following above your `handleSubmit()` function, inside `Form()`:
```jsx
const [name, setName] = useState("Learn React");
```
Several things are happening in this line of code:
- We are defining a `name` constant with the value `"Learn React"`.
- We are defining a function whose job it is to modify `name`, called `setName()`.
- `useState()` returns these two things in an array, so we are using [array destructuring](/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) to capture them both in separate variables.
### Reading state
You can see the `name` state in action right away. Add a `value` attribute to the form's input, and set its value to `name`. Your browser will render "Learn React" inside the input.
```jsx
<input
type="text"
id="new-todo-input"
className="input input__lg"
name="text"
autoComplete="off"
value={name}
/>
```
Change "Learn React" to an empty string once you're done; this is what we want for our initial state:
```jsx
const [name, setName] = useState("");
```
### Reading user input
Before we can change the value of `name`, we need to capture a user's input as they type. For this, we can listen to the `onChange` event. Let's write a `handleChange()` function, and listen for it on the `<input />` element.
```jsx
// near the top of the `Form` component
function handleChange() {
console.log("Typing!");
}
...
// Down in the return statement
<input
type="text"
id="new-todo-input"
className="input input__lg"
name="text"
autoComplete="off"
value={name}
onChange={handleChange}
/>;
```
Currently, our input's value will not change when you try to enter text into it, but your browser will log the word "Typing!" to the JavaScript console, so we know our event listener is attached to the input.
To read the user's keystrokes, we must access the input's `value` property. We can do this by reading the `event` object that `handleChange()` receives when it's called. `event`, in turn, has [a `target` property](/en-US/docs/Web/API/Event/target), which represents the element that fired the `change` event. That's our input. So, `event.target.value` is the text inside the input.
You can `console.log()` this value to see it in your browser's console. Try updating the `handleChange()` function as follows, and typing in the input to see the result in your console:
```jsx
function handleChange(event) {
console.log(event.target.value);
}
```
### Updating state
Logging isn't enough β we want to actually store what the user types and render it in the input! Change your `console.log()` call to `setName()`, as shown below:
```jsx
function handleChange(event) {
setName(event.target.value);
}
```
Now when you type in the input, your keystrokes will fill out the input, as you might expect.
We have one more step: we need to change our `handleSubmit()` function so that it calls `props.addTask` with `name` as an argument. Remember our callback prop? This will serve to send the task back to the `App` component, so we can add it to our list of tasks at some later date. As a matter of good practice, you should clear the input after your form is submitted, so we'll call `setName()` again with an empty string to do so:
```jsx
function handleSubmit(event) {
event.preventDefault();
props.addTask(name);
setName("");
}
```
At last, you can type something into the input field in your browser and click _Add_ β whatever you typed will appear in an alert dialog.
Your `Form.jsx` file should now read like this:
```jsx
import { useState } from "react";
function Form(props) {
const [name, setName] = useState("");
function handleChange(event) {
setName(event.target.value);
}
function handleSubmit(event) {
event.preventDefault();
props.addTask(name);
setName("");
}
return (
<form onSubmit={handleSubmit}>
<h2 className="label-wrapper">
<label htmlFor="new-todo-input" className="label__lg">
What needs to be done?
</label>
</h2>
<input
type="text"
id="new-todo-input"
className="input input__lg"
name="text"
autoComplete="off"
value={name}
onChange={handleChange}
/>
<button type="submit" className="btn btn__primary btn__lg">
Add
</button>
</form>
);
}
export default Form;
```
> **Note:** You'll notice that you are able to submit empty tasks by just pressing the `Add` button without entering a task name. Can you think of a way to prevent this? As a hint, you probably need to add some kind of check into the `handleSubmit()` function.
## Putting it all together: Adding a task
Now that we've practiced with events, callback props, and hooks, we're ready to write functionality that will allow a user to add a new task from their browser.
### Tasks as state
We need to import `useState` into `App.jsx` so that we can store our tasks in state. Add the following to the top of your `App.jsx` file:
```jsx
import { useState } from "react";
```
We want to pass `props.tasks` into the `useState()` hook β this will preserve its initial state. Add the following right at the top of your `App()` function definition:
```jsx
const [tasks, setTasks] = useState(props.tasks);
```
Now, we can change our `taskList` mapping so that it is the result of mapping `tasks`, instead of `props.tasks`. Your `taskList` constant declaration should now look like so:
```jsx
const taskList = tasks?.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
/>
));
```
### Adding a task
We've now got a `setTasks` hook that we can use in our `addTask()` function to update our list of tasks. There's one problem however: we can't just pass the `name` argument of `addTask()` into `setTasks`, because `tasks` is an array of objects and `name` is a string. If we tried to do this, the array would be replaced with the string.
First of all, we need to put `name` into an object that has the same structure as our existing tasks. Inside of the `addTask()` function, we will make a `newTask` object to add to the array.
We then need to make a new array with this new task added to it and then update the state of the tasks data to this new state. To do this, we can use spread syntax to [copy the existing array](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#copy_an_array), and add our object at the end. We then pass this array into `setTasks()` to update the state.
Putting that all together, your `addTask()` function should read like so:
```jsx
function addTask(name) {
const newTask = { id: "id", name, completed: false };
setTasks([...tasks, newTask]);
}
```
Now you can use the browser to add a task to our data! Type anything into the form and click "Add" (or press the <kbd>Enter</kbd> key) and you'll see your new todo item appear in the UI!
**However, we have another problem**: our `addTask()` function is giving each task the same `id`. This is bad for accessibility, and makes it impossible for React to tell future tasks apart with the `key` prop. In fact, React will give you a warning in your DevTools console β "Warning: Encountered two children with the same keyβ¦"
We need to fix this. Making unique identifiers is a hard problem β one for which the JavaScript community has written some helpful libraries. We'll use [nanoid](https://github.com/ai/nanoid) because it's tiny and it works.
Make sure you're in the root directory of your application and run the following terminal command:
```bash
npm install nanoid
```
> **Note:** If you're using yarn, you'll need the following instead: `yarn add nanoid`.
Now we can use `nanoid` to create unique IDs for our new tasks. First of all, import it by including the following line at the top of `App.jsx`:
```jsx
import { nanoid } from "nanoid";
```
Now let's update `addTask()` so that each task ID becomes a prefix `todo-` plus a unique string generated by nanoid. Update your `newTask` constant declaration to this:
```jsx
const newTask = { id: `todo-${nanoid()}`, name, completed: false };
```
Save everything, and try your app again β now you can add tasks without getting that warning about duplicate IDs.
## Detour: counting tasks
Now that we can add new tasks, you may notice a problem: our heading reads "3 tasks remaining" no matter how many tasks we have! We can fix this by counting the length of `taskList` and changing the text of our heading accordingly.
Add this inside your `App()` definition, before the return statement:
```jsx
const headingText = `${taskList.length} tasks remaining`;
```
This is almost right, except that if our list ever contains a single task, the heading will still use the word "tasks". We can make this a variable, too. Update the code you just added as follows:
```jsx
const tasksNoun = taskList.length !== 1 ? "tasks" : "task";
const headingText = `${taskList.length} ${tasksNoun} remaining`;
```
Now you can replace the list heading's text content with the `headingText` variable. Update your `<h2>` like so:
```jsx
<h2 id="list-heading">{headingText}</h2>
```
Save the file, go back to your browser, and try adding some tasks: the count should now update as expected.
## Completing a task
You might notice that, when you click on a checkbox, it checks and unchecks appropriately. As a feature of HTML, the browser knows how to remember which checkbox inputs are checked or unchecked without our help. This feature hides a problem, however: toggling a checkbox doesn't change the state in our React application. This means that the browser and our app are now out-of-sync. We have to write our own code to put the browser back in sync with our app.
### Proving the bug
Before we fix the problem, let's observe it happening.
We'll start by writing a `toggleTaskCompleted()` function in our `App()` component. This function will have an `id` parameter, but we're not going to use it yet. For now, we'll log the first task in the array to the console β we're going to inspect what happens when we check or uncheck it in our browser:
Add this just above your `taskList` constant declaration:
```jsx
function toggleTaskCompleted(id) {
console.log(tasks[0]);
}
```
Next, we'll add `toggleTaskCompleted` to the props of each `<Todo />` component rendered inside our `taskList`; update it like so:
```jsx
const taskList = tasks.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
toggleTaskCompleted={toggleTaskCompleted}
/>
));
```
Next, go over to your `Todo.jsx` component and add an `onChange` handler to your `<input />` element, which should use an anonymous function to call `props.toggleTaskCompleted()` with a parameter of `props.id`. The `<input />` should now look like this:
```jsx
<input
id={props.id}
type="checkbox"
defaultChecked={props.completed}
onChange={() => props.toggleTaskCompleted(props.id)}
/>
```
Save everything and return to your browser and notice that our first task, Eat, is checked. Open your JavaScript console, then click on the checkbox next to Eat. It unchecks, as we expect. Your JavaScript console, however, will log something like this:
```plain
Object { id: "task-0", name: "Eat", completed: true }
```
The checkbox unchecks in the browser, but our console tells us that Eat is still completed. We will fix that next!
### Synchronizing the browser with our data
Let's revisit our `toggleTaskCompleted()` function in `App.jsx`. We want it to change the `completed` property of only the task that was toggled, and leave all the others alone. To do this, we'll `map()` over the task list and just change the one we completed.
Update your `toggleTaskCompleted()` function to the following:
```jsx
function toggleTaskCompleted(id) {
const updatedTasks = tasks.map((task) => {
// if this task has the same ID as the edited task
if (id === task.id) {
// use object spread to make a new object
// whose `completed` prop has been inverted
return { ...task, completed: !task.completed };
}
return task;
});
setTasks(updatedTasks);
}
```
Here, we define an `updatedTasks` constant that maps over the original `tasks` array. If the task's `id` property matches the `id` provided to the function, we use [object spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) to create a new object, and toggle the `completed` property of that object before returning it. If it doesn't match, we return the original object.
Then we call `setTasks()` with this new array in order to update our state.
## Deleting a task
Deleting a task will follow a similar pattern to toggling its completed state: we need to define a function for updating our state, then pass that function into `<Todo />` as a prop and call it when the right event happens.
### The `deleteTask` callback prop
Here we'll start by writing a `deleteTask()` function in your `App` component. Like `toggleTaskCompleted()`, this function will take an `id` parameter, and we will log that `id` to the console to start with. Add the following below `toggleTaskCompleted()`:
```jsx
function deleteTask(id) {
console.log(id);
}
```
Next, add another callback prop to our array of `<Todo />` components:
```jsx
const taskList = tasks.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
toggleTaskCompleted={toggleTaskCompleted}
deleteTask={deleteTask}
/>
));
```
In `Todo.jsx`, we want to call `props.deleteTask()` when the "Delete" button is pressed. `deleteTask()` needs to know the ID of the task that called it, so it can delete the correct task from the state.
Update the "Delete" button inside `Todo.jsx`, like so:
```jsx
<button
type="button"
className="btn btn__danger"
onClick={() => props.deleteTask(props.id)}>
Delete <span className="visually-hidden">{props.name}</span>
</button>
```
Now when you click on any of the "Delete" buttons in the app, your browser console should log the ID of the related task.
At this point, your `Todo.jsx` file should look like this:
```jsx
function Todo(props) {
return (
<li className="todo stack-small">
<div className="c-cb">
<input
id={props.id}
type="checkbox"
defaultChecked={props.completed}
onChange={() => props.toggleTaskCompleted(props.id)}
/>
<label className="todo-label" htmlFor={props.id}>
{props.name}
</label>
</div>
<div className="btn-group">
<button type="button" className="btn">
Edit <span className="visually-hidden">{props.name}</span>
</button>
<button
type="button"
className="btn btn__danger"
onClick={() => props.deleteTask(props.id)}>
Delete <span className="visually-hidden">{props.name}</span>
</button>
</div>
</li>
);
}
export default Todo;
```
## Deleting tasks from state and UI
Now that we know `deleteTask()` is invoked correctly, we can call our `setTasks()` hook in `deleteTask()` to actually delete that task from the app's state as well as visually in the app UI. Since `setTasks()` expects an array as an argument, we should provide it with a new array that copies the existing tasks, _excluding_ the task whose ID matches the one passed into `deleteTask()`.
This is a perfect opportunity to use [`Array.prototype.filter()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter). We can test each task, and exclude a task from the new array if its `id` prop matches the `id` argument passed into `deleteTask()`.
Update the `deleteTask()` function inside your `App.jsx` file as follows:
```jsx
function deleteTask(id) {
const remainingTasks = tasks.filter((task) => id !== task.id);
setTasks(remainingTasks);
}
```
Try your app out again. Now you should be able to delete a task from your app!
At this point, your `App.jsx` file should look like this:
```jsx
import { useState } from "react";
import { nanoid } from "nanoid";
import Todo from "./components/Todo";
import Form from "./components/Form";
import FilterButton from "./components/FilterButton";
function App(props) {
function addTask(name) {
const newTask = { id: `todo-${nanoid()}`, name, completed: false };
setTasks([...tasks, newTask]);
}
function toggleTaskCompleted(id) {
const updatedTasks = tasks.map((task) => {
// if this task has the same ID as the edited task
if (id === task.id) {
// use object spread to make a new object
// whose `completed` prop has been inverted
return { ...task, completed: !task.completed };
}
return task;
});
setTasks(updatedTasks);
}
function deleteTask(id) {
const remainingTasks = tasks.filter((task) => id !== task.id);
setTasks(remainingTasks);
}
const [tasks, setTasks] = useState(props.tasks);
const taskList = tasks?.map((task) => (
<Todo
id={task.id}
name={task.name}
completed={task.completed}
key={task.id}
toggleTaskCompleted={toggleTaskCompleted}
deleteTask={deleteTask}
/>
));
const tasksNoun = taskList.length !== 1 ? "tasks" : "task";
const headingText = `${taskList.length} ${tasksNoun} remaining`;
return (
<div className="todoapp stack-large">
<h1>TodoMatic</h1>
<Form addTask={addTask} />
<div className="filters btn-group stack-exception">
<FilterButton />
<FilterButton />
<FilterButton />
</div>
<h2 id="list-heading">{headingText}</h2>
<ul
role="list"
className="todo-list stack-large stack-exception"
aria-labelledby="list-heading">
{taskList}
</ul>
</div>
);
}
export default App;
```
## Summary
That's enough for one article. Here we've given you the lowdown on how React deals with events and handles state, and implemented functionality to add tasks, delete tasks, and toggle tasks as completed. We are nearly there. In the next article we'll implement functionality to edit existing tasks and filter the list of tasks between all, completed, and incomplete tasks. We'll look at conditional UI rendering along the way.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_components","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_interactivity_filtering_conditional_rendering", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/vue_conditional_rendering/index.md | ---
title: "Vue conditional rendering: editing existing todos"
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_refs_focus_management", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Now it is time to add one of the major parts of functionality that we're still missing β the ability to edit existing todo items. To do this, we will take advantage of Vue's conditional rendering capabilities β namely `v-if` and `v-else` β to allow us to toggle between the existing todo item view, and an edit view where you can update todo item labels. We'll also look at adding functionality to delete todo items.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn how to do conditional rendering in Vue.</td>
</tr>
</tbody>
</table>
## Creating an editing component
We can start by creating a separate component to handle the editing functionality. In your `components` directory, create a new file called `ToDoItemEditForm.vue`. Copy the following code into that file:
```html
<template>
<form class="stack-small" @submit.prevent="onSubmit">
<div>
<label class="edit-label">Edit Name for "\{{label}}"</label>
<input
:id="id"
type="text"
autocomplete="off"
v-model.lazy.trim="newLabel" />
</div>
<div class="btn-group">
<button type="button" class="btn" @click="onCancel">
Cancel
<span class="visually-hidden">editing \{{label}}</span>
</button>
<button type="submit" class="btn btn__primary">
Save
<span class="visually-hidden">edit for \{{label}}</span>
</button>
</div>
</form>
</template>
<script>
export default {
props: {
label: {
type: String,
required: true,
},
id: {
type: String,
required: true,
},
},
data() {
return {
newLabel: this.label,
};
},
methods: {
onSubmit() {
if (this.newLabel && this.newLabel !== this.label) {
this.$emit("item-edited", this.newLabel);
}
},
onCancel() {
this.$emit("edit-cancelled");
},
},
};
</script>
<style scoped>
.edit-label {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #0b0c0c;
display: block;
margin-bottom: 5px;
}
input {
display: inline-block;
margin-top: 0.4rem;
width: 100%;
min-height: 4.4rem;
padding: 0.4rem 0.8rem;
border: 2px solid #565656;
}
form {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
form > * {
flex: 0 0 100%;
}
</style>
```
> **Note:** Walk through the above code then read the below description to make sure you understand everything the component is doing before moving on. This is a useful way to help reinforce everything you've learned so far.
This code sets up the core of the edit functionality. We create a form with an `<input>` field for editing the name of our to-do.
There is a "Save" button and a "Cancel" button:
- When the "Save" button is clicked, the component emits the new label via an `item-edited` event.
- When the "Cancel" button is clicked, the component signals this by emitting an `edit-cancelled` event.
## Modifying our ToDoItem component
Before we can add `ToDoItemEditForm` to our app, we need to make a few modifications to our `ToDoItem` component. Specifically, we need to add a variable to track if the item is being edited, and a button to toggle that variable. We'll also add a `Delete` button since deletion is closely related.
Update your `ToDoItem`'s template as shown below.
```html
<template>
<div class="stack-small">
<div class="custom-checkbox">
<input
type="checkbox"
class="checkbox"
:id="id"
:checked="isDone"
@change="$emit('checkbox-changed')" />
<label :for="id" class="checkbox-label">\{{label}}</label>
</div>
<div class="btn-group">
<button type="button" class="btn" @click="toggleToItemEditForm">
Edit <span class="visually-hidden">\{{label}}</span>
</button>
<button type="button" class="btn btn__danger" @click="deleteToDo">
Delete <span class="visually-hidden">\{{label}}</span>
</button>
</div>
</div>
</template>
```
We've added a wrapper `<div>` around the whole template for layout purposes.
We've also added "Edit" and "Delete" buttons:
- The "Edit" button, when clicked, will toggle displaying the `ToDoItemEditForm` component so we can use it to edit our todo item, via an event handler function called `toggleToItemEditForm()`. This handler will set an `isEditing` flag to true. To do that, we'll need to first define it inside our `data()` property.
- The "Delete" button, when clicked, will delete the todo item via an event handler function called `deleteToDo()`. In this handler we'll emit an `item-deleted` event to our parent component so the list can be updated.
Let's define our click handlers, and the necessary `isEditing` flag.
Add `isEditing` below your existing `isDone` data point:
```js
data() {
return {
isDone: this.done,
isEditing: false
};
}
```
Now add your methods inside a methods property, right below your `data()` property:
```js
methods: {
deleteToDo() {
this.$emit('item-deleted');
},
toggleToItemEditForm() {
this.isEditing = true;
}
}
```
## Conditionally displaying components via v-if and v-else
Now we have an `isEditing` flag that we can use to signify that the item is being edited (or not). If `isEditing` is true, we want to use that flag to display our `ToDoItemEditForm` instead of the checkbox. To do that, we'll use another Vue directive: [`v-if`](https://vuejs.org/api/built-in-directives.html#v-if).
The `v-if` directive will only render a block if the value passed to it is truthy. This is similar to how an `if` statement works in JavaScript. `v-if` also has corresponding [`v-else-if`](https://vuejs.org/api/built-in-directives.html#v-else-if) and [`v-else`](https://vuejs.org/api/built-in-directives.html#v-else) directives to provide the equivalent of JavaScript `else if` and `else` logic inside Vue templates.
It's important to note that `v-else` and `v-else-if` blocks need to be the first sibling of a `v-if`/`v-else-if` block, otherwise Vue will not recognize them. You can also attach `v-if` to a `<template>` tag if you need to conditionally render an entire template.
Lastly, you can use a `v-if` + `v-else` at the root of your component to display only one block or another, since Vue will only render one of these blocks at a time. We'll do this in our app, as it will allow us to replace the code that displays our to-do item with the edit form.
First of all add `v-if="!isEditing"` to the root `<div>` in your `ToDoItem` component,
```html
<div class="stack-small" v-if="!isEditing"></div>
```
Next, below that `<div>`'s closing tag add the following line:
```html
<to-do-item-edit-form v-else :id="id" :label="label"></to-do-item-edit-form>
```
We also need to import and register the `ToDoItemEditForm` component, so we can use it inside this template. Add this line at the top of your `<script>` element:
```js
import ToDoItemEditForm from "./ToDoItemEditForm";
```
And add a `components` property above the `props` property inside the component object:
```js
components: {
ToDoItemEditForm
},
```
Now, if you go to your app and click a todo item's "Edit" button, you should see the checkbox replaced with the edit form.

However, there's currently no way to go back. To fix that, we need to add some more event handlers to our component.
## Getting back out of edit mode
First, we need to add an `itemEdited()` method to our `ToDoItem` component's `methods`. This method should take the new item label as an argument, emit an `itemEdited` event to the parent component, and set `isEditing` to `false`.
Add it now, below your existing methods:
```js
itemEdited(newLabel) {
this.$emit('item-edited', newLabel);
this.isEditing = false;
}
```
Next, we'll need an `editCancelled()` method. This method will take no arguments and just serve to set `isEditing` back to `false`. Add this method below the previous one:
```js
editCancelled() {
this.isEditing = false;
}
```
Last for this section, we'll add event handlers for the events emitted by the `ToDoItemEditForm` component, and attach the appropriate methods to each event.
Update your `<to-do-item-edit-form></to-do-item-edit-form>` call to look like so:
```html
<to-do-item-edit-form
v-else
:id="id"
:label="label"
@item-edited="itemEdited"
@edit-cancelled="editCancelled">
</to-do-item-edit-form>
```
## Updating and deleting todo items
Now we can toggle between the edit form and the checkbox. However, we haven't actually handled updating the `ToDoItems` array back in `App.vue`. To fix that, we need to listen for the `item-edited` event, and update the list accordingly. We'll also want to handle the delete event so that we can delete todo items.
Add the following new methods to your `App.vue`'s component object, below the existing methods inside the `methods` property:
```js
deleteToDo(toDoId) {
const itemIndex = this.ToDoItems.findIndex((item) => item.id === toDoId);
this.ToDoItems.splice(itemIndex, 1);
},
editToDo(toDoId, newLabel) {
const toDoToEdit = this.ToDoItems.find((item) => item.id === toDoId);
toDoToEdit.label = newLabel;
}
```
Next, we'll add the event listeners for the `item-deleted` and `item-edited` events:
- For `item-deleted`, you'll need to pass the `item.id` to the method.
- For `item-edited`, you'll need to pass the `item.id` and the special `$event` variable. This is a special Vue variable used to pass event data to methods. When using native HTML events (like `click`), this will pass the native event object to your method.
Update the `<to-do-item></to-do-item>` call inside the `App.vue` template to look like this:
```html
<to-do-item
:label="item.label"
:done="item.done"
:id="item.id"
@checkbox-changed="updateDoneStatus(item.id)"
@item-deleted="deleteToDo(item.id)"
@item-edited="editToDo(item.id, $event)">
</to-do-item>
```
And there you have it β you should now be able to edit and delete items from the list!
## Fixing a small bug with isDone status
This is great so far, but we've actually introduced a bug by adding in the edit functionality. Try doing this:
1. Check (or uncheck) one of the todo checkboxes.
2. Press the "Edit" button for that todo item.
3. Cancel the edit by pressing the "Cancel" button.
Note the state of the checkbox after you cancel β not only has the app forgotten the state of the checkbox, but the done status of that todo item is now out of whack. If you try checking (or unchecking) it again, the completed count will change in the opposite way to what you'd expect. This is because the `isDone` inside `data` is only given the value `this.done` on component load.
Fixing this is fortunately quite easy β we can do this by converting our `isDone` data item into a [computed property](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties) β another advantage of computed properties is that they preserve [reactivity](https://vuejs.org/guide/essentials/reactivity-fundamentals.html), meaning (among other things) that their state is saved when the template changes like ours is now doing.
So, let's implement the fix in `ToDoItem.vue`:
1. Remove the following line from inside our `data()` property:
```js
isDone: this.done,
```
2. Add the following block below the data() { } block:
```js
computed: {
isDone() {
return this.done;
}
},
```
Now when you save and reload, you'll find that the problem is solved β the checkbox state is now preserved when you switch between todo item templates.
## Understanding the tangle of events
One of the most potentially confusing parts is the tangle of standard and custom events we've used to trigger all the interactivity in our app. To understand this better, it is a good idea to write out a flow chart, description, or diagram of what events are emitted where, where they are being listened for, and what happens as a result of them firing.
### App.vue
`<to-do-form>` listens for:
- `todo-added` event emitted by the `onSubmit()` method inside the `ToDoForm` component when the form is submitted.
**Result**: `addToDo()` method invoked to add new todo item to the `ToDoItems` array.
`<to-do-item>` listens for:
- `checkbox-changed` event emitted by the checkbox `<input>` inside the `ToDoItem` component when it is checked or unchecked.
**Result**: `updateDoneStatus()` method invoked to update done status of associated todo item.
- `item-deleted` event emitted by the `deleteToDo()` method inside the `ToDoItem` component when the "Delete" button is pressed.
**Result**: `deleteToDo()` method invoked to delete associated todo item.
- `item-edited` event emitted by the `itemEdited()` method inside the `ToDoItem` component when the `item-edited` event emitted by the `onSubmit()` method inside the `ToDoItemEditForm` has been successfully listened for. Yes, this is a chain of two different `item-edited` events!
**Result**: `editToDo()` method invoked to update label of associated todo item.
### ToDoForm.vue
`<form>` listens for `submit` event.
**Result**: `onSubmit()` method is invoked, which checks that the new label is not empty, then emits the `todo-added` event (which is then listened for inside `App.vue`, see above), and finally clears the new label `<input>`.
### ToDoItem.vue
The `<input>` of `type="checkbox"` listens for `change` events.
**Result**: `checkbox-changed` event emitted when the checkbox is checked/unchecked (which is then listened for inside `App.vue`; see above).
"Edit" `<button>` listens for `click` event.
**Result**: `toggleToItemEditForm()` method is invoked, which toggles `this.isEditing` to `true`, which in turn displays the todo item's edit form on re-render.
"Delete" `<button>` listens for `click` event.
**Result**: `deleteToDo()` method is invoked, which emits the `item-deleted` event (which is then listened for inside `App.vue`; see above).
`<to-do-item-edit-form>` listens for:
- `item-edited` event emitted by the `onSubmit()` method inside the `ToDoItemEditForm` component when the form is successfully submitted.
**Result**: `itemEdited()` method is invoked, which emits the `item-edited` event (which is then listened for inside `App.vue`, see above), and sets `this.isEditing` back to `false`, so that the edit form is no longer shown on re-render.
- `edit-cancelled` event emitted by the `onCancel()` method inside the `ToDoItemEditForm` component when the "Cancel" button is clicked.
**Result**: `editCancelled()` method is invoked, which sets `this.isEditing` back to `false`, so that the edit form is no longer shown on re-render.
### ToDoItemEditForm.vue
`<form>` listens for `submit` event.
**Result**: `onSubmit()` method is invoked, which checks to see if the new label value is not blank, and not the same as the old one, and if so emits the `item-edited` event (which is then listened for inside `ToDoItem.vue`, see above).
"Cancel" `<button>` listens for `click` event.
**Result**: `onCancel()` method is invoked, which emits the `edit-cancelled` event (which is then listened for inside `ToDoItem.vue`, see above).
## Summary
This article has been fairly intense, and we covered a lot here. We've now got edit and delete functionality in our app, which is fairly exciting. We are nearing the end of our Vue series now. The last bit of functionality to look at is focus management, or put another way, how we can improve our app's keyboard accessibility.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_refs_focus_management", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/svelte_deployment_next/index.md | ---
title: Deployment and next steps
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
In the previous article we learned about Svelte's TypeScript support, and how to use it to make your application more robust. In this final article we will look at how to deploy your application and get it online, and also share some of the resources that you should go on to, to continue your Svelte learning journey.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
You'll need a terminal with node + npm installed to compile and build
your app.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
Learn how to prepare our Svelte app for production, and what learning
resources you should visit next.
</td>
</tr>
</tbody>
</table>
## Code along with us
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/08-next-steps
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/08-next-steps
```
Remember to run `npm install && npm run dev` to start your app in development mode.
## Compiling our app
So far we've been running our app in development mode with `npm run dev`. As we saw earlier, this instruction tells Svelte to compile our components and JavaScript files into a `public/build/bundle.js` file and all the CSS sections of our components into `public/build/bundle.css`. It also starts a development server and watches for changes, recompiling the app and refreshing the page when a change occurs.
Your generated `bundle.js` and `bundle.css` files will be something like this (file size on the left):
```plain
504 Jul 13 02:43 bundle.css
95981 Jul 13 02:43 bundle.js
```
To compile our application for production we have to run `npm run build` instead. In this case, Svelte won't launch a web server or keep watching for changes. It will however minify and compress our JavaScript files using [terser](https://terser.org/).
So, after running `npm run build`, our generated `bundle.js` and `bundle.css` files will be more like this:
```plain
504 Jul 13 02:43 bundle.css
21782 Jul 13 02:43 bundle.js
```
Try running `npm run build` in your app's root directory now. You might get a warning, but you can ignore this for now.
Our whole app is now just 21 KB β 8.3 KB when gzipped. There are no additional runtimes or dependencies to download, parse, execute, and keep running in memory. Svelte analyzed our components and compiled the code to vanilla JavaScript.
## A look behind the Svelte compilation process
By default, when you create a new app with `npx degit sveltejs/template my-svelte-project`, Svelte will use [rollup](https://rollupjs.org/) as the module bundler.
> **Note:** There is also an official template for using [webpack](https://webpack.js.org/) and also many [community-maintained plugins](https://github.com/sveltejs/integrations#bundler-plugins) for other bundlers.
In the file `package.json` you can see that the `build` and `dev` scripts are just calling rollup:
```json
"scripts": {
"build": "rollup -c",
"dev": "rollup -c -w",
"start": "sirv public"
},
```
In the `dev` script we are passing the `-w` argument, which tells rollup to watch files and rebuild on changes.
If we have a look at the `rollup.config.js` file, we can see that the Svelte compiler is just a rollup plugin:
```js
import svelte from 'rollup-plugin-svelte';
// β¦
import { terser } from 'rollup-plugin-terser';
const production = !process.env.ROLLUP_WATCH;
export default {
input: 'src/main.js',
output: {
sourcemap: true,
format: 'iife',
name: 'app',
file: 'public/build/bundle.js'
},
plugins: [
svelte({
// enable run-time checks when not in production
dev: !production,
// we'll extract any component CSS out into
// a separate file - better for performance
css: (css) => {
css.write('public/build/bundle.css');
}
}),
```
Later on in the same file you'll also see how rollup minimizes our scripts in production mode and launches a local server in development mode:
```js
// In dev mode, call `npm run start` once
// the bundle has been generated
!production && serve(),
// Watch the `public` directory and refresh the
// browser on changes when not in production
!production && livereload('public'),
// If we're building for production (npm run build
// instead of npm run dev), minify
production && terser()
],
```
There are [many plugins for rollup](https://github.com/rollup/awesome) that allow you to customize its behavior. A particularly useful plugin which is also maintained by the Svelte team is [svelte-preprocess](https://github.com/sveltejs/svelte-preprocess), which pre-processes many different languages in Svelte files such as PostCSS, SCSS, Less, CoffeeScript, SASS, and TypeScript.
## Deploying your Svelte application
From the point of view of a web server, a Svelte application is nothing more than a bunch of HTML, CSS, and JavaScript files. All you need is a web server capable of serving static files, which means you have plenty of options to choose from. Let's look at a couple of examples.
> **Note:** the following section could be applied to any client-side static website requiring a build step, not just Svelte apps.
### Deploying with Vercel
One of the easiest ways to deploy a Svelte application is using [Vercel](https://vercel.com/home). Vercel is a cloud platform specifically tailored for static sites, which has out-of-the-box support for most common front-end tools, Svelte being one of them.
To deploy our app, follow these steps.
1. [register for an account with Vercel](https://vercel.com/signup).
2. Navigate to the root of your app and run `npx vercel`; the first time you do it, you'll be prompted to enter your email address, and follow the steps in the email sent to that address, for security purposes.
3. Run `npx vercel` again, and you'll be prompted to answer a few questions, like this:
```bash
npx vercel
```
```plain
Vercel CLI 19.1.2
? Set up and deploy "./mdn-svelte-tutorial"? [Y/n] y
? Which scope do you want to deploy to? opensas
? Link to existing project? [y/N] n
? What's your project's name? mdn-svelte-tutorial
? In which directory is your code located? ./
Auto-detected Project Settings (Svelte):
- Build Command: `npm run build` or `rollup -c`
- Output Directory: public
- Development Command: sirv public --single --dev --port $PORT
? Want to override the settings? [y/N] n
Linked to opensas/mdn-svelte-tutorial (created .vercel)
Inspect: https://vercel.com/opensas/mdn-svelte-tutorial/[...] [1s]
β
Production: https://mdn-svelte-tutorial.vercel.app [copied to clipboard] [19s]
Deployed to production. Run `vercel --prod` to overwrite later (https://vercel.link/2F).
To change the domain or build command, go to https://zeit.co/opensas/mdn-svelte-tutorial/settings
```
4. Accept all the defaults, and you'll be fine.
5. Once it has finished deploying, go to the "Production" URL in your browser, and you'll see the app deployed!
You can also [import a Svelte git project](https://vercel.com/import/svelte) into Vercel from [GitHub](https://github.com/), [GitLab](https://about.gitlab.com/), or [BitBucket](https://bitbucket.org/product).
> **Note:** you can globally install Vercel with `npm i -g vercel` so you don't have to use `npx` to run it.
### Automatic deployment to GitLab pages
For hosting static files there are several online services that allow you to automatically deploy your site whenever you push changes to a git repository. Most of them involve setting up a deployment pipeline that gets triggered on every `git push`, and takes care of building and deploying your website.
To demonstrate this, we will deploy our todos app to [GitLab Pages](https://about.gitlab.com/stages-devops-lifecycle/pages/).
1. First you'll have to [register at GitLab](https://gitlab.com/users/sign_up) and then [create a new project](https://gitlab.com/projects/new). Give you new project a short, easy name like "mdn-svelte-todo". You will have a remote URL that points to your new GitLab git repository, like `[email protected]:[your-user]/[your-project].git`.
2. Before you start to upload content to your git repository, it is a good practice to add a `.gitignore` file to tell git which files to exclude from source control. In our case we will tell git to exclude files in the `node_modules` directory by creating a `.gitignore` file in the root folder of your local project, with the following content:
```bash
node_modules/
```
3. Now let's go back to GitLab. After creating a new repo GitLab will greet you with a message explaining different options to upload your existing files. Follow the steps listed under the _Push an existing folder_ heading:
```bash
cd your_root_directory # Go into your project's root directory
git init
git remote add origin https://gitlab.com/[your-user]/mdn-svelte-todo.git
git add .
git commit -m "Initial commit"
git push -u origin main
```
> **Note:** You could use [the `git` protocol](https://git-scm.com/book/en/v2/Git-on-the-Server-The-Protocols#_the_git_protocol) instead of `https`, which is faster and saves you from typing your username and password every time you access your origin repo. To use it you'll have to [create an SSH key pair](https://docs.gitlab.com/ee/user/ssh.html#generate-an-ssh-key-pair). Your origin URL will be like this: `[email protected]:[your-user]/mdn-svelte-todo.git`.
With these instructions we initialize a local git repository, then set our remote origin (where we will push our code to) as our repo on GitLab. Next we commit all the files to the local git repo, and then push those to the remote origin on GitLab.
GitLab uses a built-in tool called GitLab CI/CD to build your site and publish it to the GitLab Pages server. The sequence of scripts that GitLab CI/CD runs to accomplish this task is created from a file named `.gitlab-ci.yml`, which you can create and modify at will. A specific job called `pages` in the configuration file will make GitLab aware that you are deploying a GitLab Pages website.
Let's have a go at doing this now.
1. Create a `.gitlab-ci.yml` file inside your project's root and give it the following content:
```yaml
image: node:latest
pages:
stage: deploy
script:
- npm install
- npm run build
artifacts:
paths:
- public
only:
- main
```
Here we are telling GitLab to use an image with the latest version of node to build our app. Next we are declaring a `pages` job, to enable GitLab Pages. Whenever there's a push to our repo, GitLab will run `npm install` and `npm run build` to build our application. We are also telling GitLab to deploy the contents of the `public` folder. On the last line, we are configuring GitLab to redeploy our app only when there's a push to our main branch.
2. Since our app will be published at a subdirectory (like `https://your-user.gitlab.io/mdn-svelte-todo`), we'll have to make the references to the JavaScript and CSS files in our `public/index.html` file relative. To do this, we just remove the leading slashes (`/`) from the `/global.css`, `/build/bundle.css`, and `/build/bundle.js` URLs, like this:
```html
<title>Svelte To-Do list</title>
<link rel="icon" type="image/png" href="favicon.png" />
<link rel="stylesheet" href="global.css" />
<link rel="stylesheet" href="build/bundle.css" />
<script defer src="build/bundle.js"></script>
```
Do this now.
3. Now we just have to commit and push our changes to GitLab. Do this by running the following commands:
```bash
git add public/index.html
git add .gitlab-ci.yml
git commit -m "Added .gitlab-ci.yml file and fixed index.html absolute paths"
git push
```
Whenever there's a job running GitLab will display an icon showing the process of the job. Clicking on it will let you inspect the output of the job.

You can also check the progress of the current and previous jobs from the _CI / CD_ > _Jobs_ menu option of your GitLab project.

Once GitLab finishes building and publishing your app, it will be accessible at `https://your-user.gitlab.io/mdn-svelte-todo/`; in my case it's `https://opensas.gitlab.io/mdn-svelte-todo/`. You can check your page's URL in GitLab's UI β see the _Settings_ > _Pages_ menu option.
With this configuration, whenever you push changes to the GitLab repo, the application will be automatically rebuilt and deployed to GitLab Pages.
## Learning more about Svelte
In this section we'll give you some resources and projects to go and check out, to take your Svelte learning further.
### Svelte documentation
To go further and learn more about Svelte, you should definitely visit the [Svelte homepage](https://svelte.dev/). There you'll find [many articles](https://svelte.dev/blog) explaining Svelte's philosophy. If you haven't already done it, make sure you go through the [Svelte interactive tutorial](https://learn.svelte.dev/). We already covered most of its content, so it won't take you much time to complete it β you should consider it as practice!
You can also consult the [Svelte API docs](https://svelte.dev/docs) and the available [examples](https://svelte.dev/examples/hello-world).
To understand the motivations behind Svelte, you should read [Rich Harris](https://twitter.com/Rich_Harris)'s [Rethinking reactivity](https://www.youtube.com/watch?v=AdNJ3fydeao&t=47s) presentation on YouTube. He is the creator of Svelte, so he has a couple of things to say about it. You also have the interactive slides available here which are, unsurprisingly, built with Svelte. If you liked it, you will also enjoy [The Return of 'Write Less, Do More'](https://www.youtube.com/watch?v=BzX4aTRPzno) presentation, which Rich Harris gave at [JSCAMP 2019](https://jscamp.tech/2019/).
### Related projects
There are other projects related to Svelte that are worth checking out:
- [Sapper](https://sapper.svelte.dev/): An application framework powered by Svelte that provides server-side rendering (SSR), code splitting, file-based routing and offline support, and more. Think of it as [Next.js](https://nextjs.org/) for Svelte. If you are planning to develop a fairly complex web application you should definitely have a look at this project.
- [Svelte Native](https://svelte-native.technology/): A mobile application framework powered by Svelte. Think of it as [React Native](https://reactnative.dev/) for Svelte.
- [Svelte for VS Code](https://marketplace.visualstudio.com/items?itemName=svelte.svelte-vscode): The officially supported VS Code plugin for working with `.svelte` files, which we looked at in our [TypeScript article](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript).
### Other learning resources
- There's a [complete course about Svelte and Sapper](https://frontendmasters.com/courses/svelte/) by Rich Harris, available at Frontend Masters.
- Even though Svelte is a relatively young project there are lots of tutorials and [courses](https://www.udemy.com/topic/svelte-framework/?sort=popularity) available on the web, so it's difficult to make a recommendation.
- Nevertheless, [Svelte.js β The Complete Guide](https://www.udemy.com/course/sveltejs-the-complete-guide/) by [Academind](https://academind.com/) is a very popular option with great ratings.
- [The Svelte Handbook](https://www.freecodecamp.org/news/the-svelte-handbook/), by [Flavio Copes](https://flaviocopes.com/), is also a useful reference for learning the main Svelte concepts.
- If you prefer to read books, there's [Svelte and Sapper in Action](https://www.manning.com/books/svelte-and-sapper-in-action) by [Mark Volkman](https://twitter.com/mark_volkmann), expected to be published in September 2020, but which you can already [preview online](https://livebook.manning.com/book/svelte-and-sapper-in-action/welcome/v-5/) for free.
- If you want dive deeper and understand the inner working of Svelte's compiler you should check [Tan Li Hau](https://twitter.com/lihautan)'s _Compile Svelte in your head_ blog posts. Here's [Part 1](https://lihautan.com/compile-svelte-in-your-head-part-1/), [Part 2](https://lihautan.com/compile-svelte-in-your-head-part-2/), and [Part 3](https://lihautan.com/compile-svelte-in-your-head-part-3/).
### Interacting with the community
There are a number of different ways to get support and interact with the Svelte community:
- [svelte.dev/chat](https://discord.com/invite/yy75DKs): Svelte's Discord server.
- [@sveltejs](https://twitter.com/sveltejs): The official Twitter account.
- [@sveltesociety](https://twitter.com/sveltesociety): Svelte community Twitter account.
- [Svelte Recipes](https://github.com/svelte-society/recipes-mvp#recipes-mvp): Community-driven repository of recipes, tips, and best practices to solve common problems.
- [Svelte questions on StackOverflow](https://stackoverflow.com/questions/tagged/svelte): Questions with the `svelte` tag at SO.
- [Svelte reddit community](https://www.reddit.com/r/sveltejs/): Svelte community discussion and content rating site at reddit.
- [Svelte DEV community](https://dev.to/t/svelte): A collection of Svelte-related technical articles and tutorials from the DEV.to community.
## Finito
Congratulations! You have completed the Svelte tutorial. In the previous articles we went from zero knowledge about Svelte to building and deploying a complete application.
- We learned about Svelte philosophy and what sets it apart from other front-end frameworks.
- We saw how to add dynamic behavior to our website, how to organize our app in components and different ways to share information among them.
- We took advantage of the Svelte reactivity system and learned how to avoid common pitfalls.
- We also saw some advanced concepts and techniques to interact with DOM elements and to programmatically extend HTML element capabilities using the `use` directive.
- Then we saw how to use stores to work with a central data repository, and we created our own custom store to persist our application's data to Web Storage.
- We also took a look at Svelte's TypeScript support.
In this article we've learned about a couple of zero-fuss options to deploy our app in production and seen how to set up a basic pipeline to deploy our app to GitLab on every commit. Then we provided you with a list of Svelte resources to go further with your Svelte learning.
Congratulations! After completing this series of tutorials you should have a strong base from which to start developing professional web applications with Svelte.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_TypeScript","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_getting_started", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/ember_interactivity_events_state/index.md | ---
title: "Ember interactivity: Events, classes and state"
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
At this point we'll start adding some interactivity to our app, providing the ability to add and display new todo items. Along the way, we'll look at using events in Ember, creating component classes to contain JavaScript code to control interactive features, and setting up a service to keep track of the data state of our app.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
A deeper understanding of modern JavaScript features (such as classes,
modules, etc.), will be extremely beneficial, as Ember makes heavy use
of them.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn how to create component classes and use events to control
interactivity, and keep track of app state using a service.
</td>
</tr>
</tbody>
</table>
## Adding Interactivity
Now we've got a refactored componentized version of our todo app, lets walk through how we can add the interactivity we need to make the app functional.
When beginning to think about interactivity, it's good to declare what each component's goals and responsibilities are. In the below sections we'll do this for each component, and then walk you through how the functionality can be implemented.
## Creating todos
For our card-header / todo input, we'll want to be able to submit our typed in todo task when we press the <kbd>Enter</kbd> key and have it appear in the todos list.
We want to be able to capture the text typed into the input. We do this so that our JavaScript code knows what we typed in, and we can save our todo and pass that text along to the todo list component to display.
We can capture the [`keydown`](/en-US/docs/Web/API/Element/keydown_event) event via the [on modifier](https://api.emberjs.com/ember/3.16/classes/Ember.Templates.helpers/methods/on?anchor=on), which is just Ember syntactic sugar around [`addEventListener`](/en-US/docs/Web/API/EventTarget/addEventListener) and [`removeEventListener`](/en-US/docs/Web/API/EventTarget/removeEventListener) (see [this explanation](/en-US/docs/Learn/JavaScript/Building_blocks/Events#addeventlistener_and_removeeventlistener) if needed).
Add the new line shown below to your `header.hbs` file:
```hbs
<input
class='new-todo'
aria-label='What needs to be done?'
placeholder='What needs to be done?'
autofocus
\{{on 'keydown' this.onKeyDown}}
>
```
This new attribute is inside double curly braces, which tells you it is part of Ember's dynamic templating syntax. The first argument passed to `on` is the type of event to respond to (`keydown`), and the last argument is the event handler β the code that will run in response to the `keydown` event firing. As you may expect from dealing with [vanilla JavaScript objects](/en-US/docs/Learn/JavaScript/Objects/Basics#what_is_this), the `this` keyword refers to the "context" or "scope" of the component. One component's `this` will be different from another component's `this`.
We can define what is available inside `this` by generating a component class to go along with your component. This is a vanilla JavaScript class and has no special meaning to Ember, other than _extending_ from the `Component` super-class.
To create a header class to go with your header component, type this in to your terminal:
```bash
ember generate component-class header
```
This will create the following empty class file β `todomvc/app/components/header.js`:
```js
import Component from "@glimmer/component";
export default class HeaderComponent extends Component {}
```
Inside this file we will implement the event handler code. Update the content to the following:
```js
import Component from "@glimmer/component";
import { action } from "@ember/object";
export default class HeaderComponent extends Component {
@action
onKeyDown({ target, key }) {
let text = target.value.trim();
let hasValue = Boolean(text);
if (key === "Enter" && hasValue) {
alert(text);
target.value = "";
}
}
}
```
The `@action` decorator is the only Ember-specific code here (aside from extending from the `Component` superclass, and the Ember-specific items we are importing using [JavaScript module syntax](/en-US/docs/Web/JavaScript/Guide/Modules)) β the rest of the file is vanilla JavaScript, and would work in any application. The `@action` decorator declares that the function is an "action", meaning it's a type of function that will be invoked from an event that occurred in the template. `@action` also binds the `this` of the function to the class instance.
> **Note:** A decorator is basically a wrapper function, which wraps and calls other functions or properties, providing additional functionality along the way. For example, the `@tracked` decorator (see slightly later on) runs code it is applied to, but additionally tracks it and automatically updates the app when values change. [Read JavaScript Decorators: What They Are and When to Use Them](https://www.sitepoint.com/javascript-decorators-what-they-are/) for more general information on decorators.
Coming back to our browser tab with the app running, we can type whatever we want, and when we hit <kbd>Enter</kbd> we'll be greeted with an alert message telling us exactly what we typed.

With the interactivity of the header input out of the way, we need a place to store todos so that other components can access them.
## Storing Todos with a service
Ember has built-in application-level **state** management that we can use to manage the storage of our todos and allow each of our components to access data from that application-level state. Ember calls these constructs [Services](https://guides.emberjs.com/release/services/), and they live for the entire lifetime of the page (a page refresh will clear them; persisting the data for longer is beyond the scope of this tutorial).
Run this terminal command to generate a service for us to store our todo-list data in:
```bash
ember generate service todo-data
```
This should give you a terminal output like so:
```plain
installing service
create app/services/todo-data.js
installing service-test
create tests/unit/services/todo-data-test.js
```
This creates a `todo-data.js` file inside the `todomvc/app/services` directory to contain our service, which initially contains an import statement and an empty class:
```js
import Service from "@ember/service";
export default class TodoDataService extends Service {}
```
First of all, we want to define _what a todo is_. We know that we want to track both the text of a todo, and whether or not it is completed.
Add the following `import` statement below the existing one:
```js
import { tracked } from "@glimmer/tracking";
```
Now add the following class below the previous line you added:
```js
class Todo {
@tracked text = "";
@tracked isCompleted = false;
constructor(text) {
this.text = text;
}
}
```
This class represents a todo β it contains a `@tracked text` property containing the text of the todo, and a `@tracked isCompleted` property that specifies whether the todo has been completed or not. When instantiated, a `Todo` object will have an initial `text` value equal to the text given to it when created (see below), and an `isCompleted` value of `false`. The only Ember-specific part of this class is the `@tracked` decorator β this hooks in to the reactivity system and allows Ember to update what you're seeing in your app automatically if the tracked properties change. [More information on tracked can be found here](https://api.emberjs.com/ember/3.15/functions/@glimmer%2Ftracking/tracked).
Now it's time to add to the body of the service.
First add another `import` statement below the previous one, to make actions available inside the service:
```js
import { action } from "@ember/object";
```
Update the existing `export default class TodoDataService extends Service { }` block as follows:
```js
export default class TodoDataService extends Service {
@tracked todos = [];
@action
add(text) {
let newTodo = new Todo(text);
this.todos.pushObject(newTodo);
}
}
```
Here, the `todos` property on the service will maintain our list of todos contained inside an array, and we'll mark it with `@tracked`, because when the value of `todos` is updated we want the UI to update as well.
And just like before, the `add()` function that will be called from the template gets annotated with the `@action` decorator to bind it to the class instance.
While this may look like familiar JavaScript, you may notice that we're calling the method [`pushObject()`](https://api.emberjs.com/ember/4.2/classes/ArrayProxy/methods/filterBy?anchor=pushObject) on our `todos` array.
This is because Ember extends JavaScript's Array prototype by default, giving us convenient methods to ensure Ember's tracking system knows about these changes.
There are dozens of these methods, including `pushObjects()`, `insertAt()`, or `popObject()`, which can be used with any type (not just Objects).
Ember's [ArrayProxy](https://api.emberjs.com/ember/4.2/classes/ArrayProxy) also gives us more handy methods, like `isAny()`, `findBy()`, and `filterBy()` to make life easier.
## Using the service from our header component
Now that we've defined a way to add todos, we can interact with this service from the `header.js` input component to actually start adding them.
First of all, the service needs to be injected into the template via the `@inject` decorator, which we'll rename to `@service` for semantic clarity. To do this, add the following `import` line to `header.js`, beneath the two existing `import` lines:
```js
import { inject as service } from "@ember/service";
```
With this import in place, we can now make the `todo-data` service available inside the `HeaderComponent` class via the `todos` object, using the `@service` decorator. Add the following line just below the opening `exportβ¦` line:
```js
@service('todo-data') todos;
```
Now the placeholder `alert(text);` line can be replaced with a call to our new `add()` function. Replace it with the following:
```js
this.todos.add(text);
```
If we try this out in the todo app in our browser (`npm start`, go to `localhost:4200`), it will look like nothing happens after hitting the <kbd>Enter</kbd> key (although the fact that the app builds without any errors is a good sign). Using the [Ember Inspector](https://guides.emberjs.com/release/ember-inspector/installation/) however, we can see that our todo was added:

## Displaying our todos
Now that we know that we can create todos, there needs to be a way to swap out our static "Buy Movie Tickets" todos with the todos we're actually creating. In the `TodoList` component, we'll want to get the todos out of the service, and render a `Todo` component for each todo.
In order to retrieve the todos from the service, our `TodoList` component first needs a backing component class to contain this functionality. Press <kbd>Ctrl</kbd> + <kbd>C</kbd> to stop the development server, and enter the following terminal command:
```bash
ember generate component-class todo-list
```
This generates the new component class `todomvc/app/components/todo-list.js`.
Populate this file with the following code, which exposes the `todo-data` service, via the `todos` property, to our template. This makes it accessible via `this.todos` inside both the class and the template:
```js
import Component from "@glimmer/component";
import { inject as service } from "@ember/service";
export default class TodoListComponent extends Component {
@service("todo-data") todos;
}
```
One issue here is that our service is called `todos`, but the list of todos is also called `todos`, so currently we would access the data using `this.todos.todos`. This is not intuitive, so we'll add a [getter](/en-US/docs/Web/JavaScript/Reference/Functions/get) to the `todos` service called `all`, which will represent all todos.
To do this, go back to your `todo-data.js` file and add the following below the `@tracked todos = [];` line:
```js
get all() {
return this.todos;
}
```
Now we can access the data using `this.todos.all`, which is much more intuitive. To put this in action, go to your `todo-list.hbs` component, and replace the static component calls:
```hbs
<Todo />
<Todo />
```
With a dynamic `#each` block (which is basically syntactic sugar over the top of JavaScript's [`forEach()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)) that creates a `<Todo />` component for each todo available in the list of todos returned by the service's `all()` getter:
```hbs-nolint
\{{#each this.todos.all as |todo|}}
<Todo @todo=\{{todo}} />
\{{/each}}
```
Another way to look at this:
- `this` β the rendering context / component instance.
- `todos` β a property on `this`, which we defined in the `todo-list.js` component using `@service('todo-data') todos;`. This is a reference to the `todo-data` service, allowing us to interact with the service instance directly.
- `all` β a getter on the `todo-data` service that returns all the todos.
Try starting the server again and navigating to our app, and you'll find that it works! Well, sort of. Whenever you enter a new Todo item, a new list item appears below the text input, but unfortunately it always says "Buy Movie Tickets".
This is because the text label inside each list item is hardcoded to that text, as seen in `todo.hbs`:
```hbs
<label>Buy Movie Tickets</label>
```
Update this line to use the Argument `@todo` β which will represent the Todo that we passed in to this component when it was invoked in `todo-list.hbs`, in the line `<Todo @todo=\{{todo}} />`:
```hbs
<label>\{{@todo.text}}</label>
```
OK, try it again. You should find that now the text submitted in the `<input>` is properly reflected in the UI:

## Summary
OK, so that's great progress for now. We can now add todo items to our app, and the state of the data is tracked using our service. Next we'll move on to getting our footer functionality working, including the todo counter, and look at conditional rendering, including correctly styling todos when they've been checked. We'll also wire up our "Clear completed" button.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_structure_componentization","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/angular_getting_started/index.md | ---
title: Getting started with Angular
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_getting_started
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_todo_list_beginning", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
It is now time to look at Google's Angular framework, another popular option that you'll come across often. In this article we look at what Angular has to offer, install the prerequisites and set up a sample app, and look at Angular's basic architecture.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To setup a local Angular development environment, create a starter app,
and understand the basics of how it works.
</td>
</tr>
</tbody>
</table>
## What is Angular?
Angular is a development platform, built on [TypeScript](https://www.typescriptlang.org/). As a platform, Angular includes:
- A component-based framework for building scalable web applications
- A collection of well-integrated libraries that cover a wide variety of features, including routing, forms management, client-server communication, and more
- A suite of developer tools to help you develop, build, test, and update your code
When you build applications with Angular, you're taking advantage of a platform that can scale from single-developer projects to enterprise-level applications. Angular is designed to make updating as easy as possible, so you can take advantage of the latest developments with a minimum of effort. Best of all, the Angular ecosystem consists of a diverse group of over 1.7 million developers, library authors, and content creators.
Before you start exploring the Angular platform, you should know about the Angular CLI. The Angular CLI is the fastest, easiest, and recommended way to develop Angular applications. The Angular CLI makes a number of tasks easy. Here are some examples:
<table class="standard-table">
<tbody>
<tr>
<td>
<code><a href="https://angular.io/cli/build">ng build</a></code>
</td>
<td>Compiles an Angular app into an output directory.</td>
</tr>
<tr>
<td>
<code><a href="https://angular.io/cli/serve">ng serve</a></code>
</td>
<td>Builds and serves your application, rebuilding on file changes.</td>
</tr>
<tr>
<td>
<code><a href="https://angular.io/cli/generate">ng generate</a></code>
</td>
<td>Generates or modifies files based on a schematic.</td>
</tr>
<tr>
<td>
<code><a href="https://angular.io/cli/test">ng test</a></code>
</td>
<td>Runs unit tests on a given project.</td>
</tr>
<tr>
<td>
<code><a href="https://angular.io/cli/e2e">ng e2e</a></code>
</td>
<td>
Builds and serves an Angular application, then runs end-to-end tests.
</td>
</tr>
</tbody>
</table>
You'll find the Angular CLI to be a valuable tool for building out your applications.
## What you'll build
This tutorial series guides you through building a to-do list application. Via this application you'll learn how to use Angular to manage, edit, add, delete, and filter items.
## Prerequisites
To install Angular on your local system, you need the following:
- **Node.js**
Angular requires a [current, active LTS, or maintenance LTS](https://nodejs.org/en/about/previous-releases) version of Node.js. For information about specific version requirements, see the `engines` key in the [package.json](https://unpkg.com/@angular/cli/package.json) file.
For more information on installing Node.js, see [nodejs.org](https://nodejs.org).
If you are unsure what version of Node.js runs on your system, run `node -v` in a terminal window.
- **npm package manager**
Angular, the Angular CLI, and Angular applications depend on [npm packages](https://docs.npmjs.com/getting-started/what-is-npm/) for many features and functions.
To download and install npm packages, you need an npm package manager.
This guide uses the [npm client](https://docs.npmjs.com/cli/install/) command line interface, which is installed with `Node.js` by default.
To check that you have the npm client installed, run `npm -v` in a terminal window.
## Set up your application
You can use the Angular CLI to run commands in your terminal for generating, building, testing, and deploying Angular applications.
To install the Angular CLI, run the following command in your terminal:
```bash
npm install -g @angular/cli
```
Angular CLI commands all start with `ng`, followed by what you'd like the CLI to do.
In the Desktop directory, use the following `ng new` command to create a new application called `todo`:
```bash
ng new todo --routing=false --style=css
```
The `ng new` command creates a minimal starter Angular application on your Desktop.
The additional flags, `--routing` and `--style`, define how to handle navigation and styles in the application.
This tutorial describes these features later in more detail.
If you are prompted to enforce stricter type checking, you can respond with yes.
Navigate into your new project with the following `cd` command:
```bash
cd todo
```
To run your `todo` application, use `ng serve`:
```bash
ng serve
```
When the CLI prompts you about analytics, answer `no`.
In the browser, navigate to `http://localhost:4200/` to see your new starter application.
If you change any of the source files, the application automatically reloads.
While `ng serve` is running, you might want to open a second terminal tab or window in order to run commands.
If at any point you would like to stop serving your application, press `Ctrl+c` while in the terminal.
## Get familiar with your Angular application
The application source files that this tutorial focuses on are in `src/app`.
Key files that the CLI generates automatically include the following:
1. `app.module.ts`: Specifies the files that the application uses.
This file acts as a central hub for the other files in your application.
2. `app.component.ts`: Also known as the class, contains the logic for the application's main page.
3. `app.component.html`: Contains the HTML for `AppComponent`. The contents of this file are also known as the template.
The template determines the view or what you see in the browser.
4. `app.component.css`: Contains the styles for `AppComponent`. You use this file when you want to define styles that only apply to a specific component, as opposed to your application overall.
A component in Angular is made up of three main partsβthe template, styles, and the class.
For example, `app.component.ts`, `app.component.html`, and `app.component.css` together constitute the `AppComponent`.
This structure separates the logic, view, and styles so that the application is more maintainable and scalable.
In this way, you are using the best practices from the very beginning.
The Angular CLI also generates a file for component testing called `app.component.spec.ts`, but this tutorial doesn't go into testing, so you can ignore that file.
Whenever you generate a component, the CLI creates these four files in a directory with the name you specify.
## The structure of an Angular application
Angular is built with TypeScript.
TypeScript is a superset of JavaScript meaning that any valid JavaScript is valid TypeScript.
TypeScript offers typing and a more concise syntax than plain JavaScript, which gives you a tool for creating more maintainable code and minimizing bugs.
Components are the building blocks of an Angular application.
A component includes a TypeScript class that has a `@Component()` decorator.
### The decorator
You use the `@Component()` decorator to specify metadata (HTML template and styles) about a class.
### The class
The class is where you put any logic your component needs.
This code can include functions, event listeners, properties, and references to services to name a few.
The class is in a file with a name such as `feature.component.ts`, where `feature` is the name of your component.
So, you could have files with names such as `header.component.ts`, `signup.component.ts`, or `feed.component.ts`.
You create a component with a `@Component()` decorator that has metadata that tells Angular where to find the HTML and CSS.
A typical component is as follows:
```js
import { Component } from "@angular/core";
@Component({
selector: "app-item",
// the following metadata specifies the location of the other parts of the component
templateUrl: "./item.component.html",
styleUrls: ["./item.component.css"],
})
export class ItemComponent {
// your code goes here
}
```
This component is called `ItemComponent`, and its selector is `app-item`.
You use a selector just like regular HTML tags by placing it within other templates.
When a selector is in a template, the browser renders the template of that component whenever an instance of the selector is encountered.
This tutorial guides you through creating two components and using one within the other.
**NOTE:** The name of the component above is `ItemComponent` which is also the name of the class. Why?
The names are the same simply because a component is nothing but a class supplemented by a TypeScript decorator.
Angular's component model offers strong encapsulation and an intuitive application structure.
Components also make your application easier to unit test and can improve the overall readability of your code.
### The HTML template
Every component has an HTML template that declares how that component renders.
You can define this template either inline or by file path.
To refer to an external HTML file, use the `templateUrl` property:
```js
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
})
export class AppComponent {
// code goes here
}
```
To write inline HTML, use the `template` property and write your HTML within backticks:
```js
@Component({
selector: "app-root",
template: `<h1>Hi!</h1>`,
})
export class AppComponent {
// code goes here
}
```
Angular extends HTML with additional syntax that lets you insert dynamic values from your component.
Angular automatically updates the rendered DOM when your component's state changes.
One use of this feature is inserting dynamic text, as shown in the following example.
```html
<h1>\{{ title }}</h1>
```
The double curly braces instruct Angular to interpolate the contents within them.
The value for `title` comes from the component class:
```js
import { Component } from "@angular/core";
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
title = "To do application";
}
```
When the application loads the component and its template, the browser sees the following:
```html
<h1>To do application</h1>
```
### Styles
A component can inherit global styles from the application's `styles.css` file and augment or override them with its own styles.
You can write component-specific styles directly in the `@Component()` decorator or specify the path to a CSS file.
To include the styles directly in the component decorator, use the `styles` property:
```js
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styles: ['h1 { color: red; }']
})
```
Typically, a component uses styles in a separate file using the `styleUrls` property:
```js
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
```
With component-specific styles, you can organize your CSS so that it is easily maintainable and portable.
## Summary
That's it for your first introduction to Angular. At this point you should be set up and ready to build an Angular app, and have a basic understanding of how Angular works. In the next article we'll deepen that knowledge and start to build up the structure of our to-do list application.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_deployment_next","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_todo_list_beginning", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/vue_methods_events_models/index.md | ---
title: "Adding a new todo form: Vue events, methods, and models"
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
We now have sample data in place, and a loop that takes each bit of data and renders it inside a `ToDoItem` in our app. What we really need next is the ability to allow our users to enter their own todo items into the app, and for that we'll need a text `<input>`, an event to fire when the data is submitted, a method to fire upon submission to add the data and rerender the list, and a model to control the data. This is what we'll cover in this article.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To learn about handling forms in Vue, and by association, events,
models, and methods.
</td>
</tr>
</tbody>
</table>
## Creating a New To-Do form
We now have an app that displays a list of to-do items. However, we can't update our list of items without manually changing our code! Let's fix that. Let's create a new component that will allow us to add a new to-do item.
1. In your components folder, create a new file called `ToDoForm.vue`.
2. Add a blank `<template>` and a `<script>` tag like before:
```html
<template></template>
<script>
export default {};
</script>
```
3. Let's add in an HTML form that lets you enter a new todo item and submit it into the app. We need a [`<form>`](/en-US/docs/Web/HTML/Element/form) with a [`<label>`](/en-US/docs/Web/HTML/Element/label), an [`<input>`](/en-US/docs/Web/HTML/Element/input), and a [`<button>`](/en-US/docs/Web/HTML/Element/button). Update your template as follows:
```html
<template>
<form>
<label for="new-todo-input"> What needs to be done? </label>
<input
type="text"
id="new-todo-input"
name="new-todo"
autocomplete="off" />
<button type="submit">Add</button>
</form>
</template>
```
So we now have a form component into which we can enter the title of a new todo item (which will become a label for the corresponding `ToDoItem` when it is eventually rendered).
4. Let's load this component into our app. Go back to `App.vue` and add the following `import` statement just below the previous one, inside your `<script>` element:
```js
import ToDoForm from "./components/ToDoForm";
```
5. You also need to register the new component in your `App` component β update the `components` property of the component object so that it looks like this:
```js
components: {
ToDoItem, ToDoForm,
}
```
6. Finally for this section, render your `ToDoForm` component inside your app by adding the `<to-do-form />` element inside your `App`'s `<template>`, like so:
```html
<template>
<div id="app">
<h1>My To-Do List</h1>
<to-do-form></to-do-form>
<ul>
<li v-for="item in ToDoItems" :key="item.id">
<to-do-item
:label="item.label"
:done="item.done"
:id="item.id"></to-do-item>
</li>
</ul>
</div>
</template>
```
Now when you view your running site, you should see the new form displayed.

If you fill it out and click the "Add" button, the page will post the form back to the server, but this isn't really what we want. What we actually want to do is run a method on the [`submit` event](/en-US/docs/Web/API/HTMLFormElement/submit_event) that will add the new todo to the `ToDoItem` data list defined inside `App`. To do that, we'll need to add a method to the component instance.
## Creating a method & binding it to an event with v-on
To make a method available to the `ToDoForm` component, we need to add it to the component object, and this is done inside a `methods` property to our component, which goes in the same place as `data()`, `props`, etc. The `methods` property holds any methods we might need to call in our component. When referenced, methods are fully run, so it's not a good idea to use them to display information inside the template. For displaying data that comes from calculations, you should use a `computed` property, which we'll cover later.
1. In this component, we need to add an `onSubmit()` method to a `methods` property inside the `ToDoForm` component object. We'll use this to handle the submit action.
Add this like so:
```js
export default {
methods: {
onSubmit() {
console.log("form submitted");
},
},
};
```
2. Next we need to bind the method to our `<form>` element's `submit` event handler. Much like how Vue uses the [`v-bind`](https://vuejs.org/api/built-in-directives.html#v-bind) syntax for binding attributes, Vue has a special directive for event handling: [`v-on`](https://vuejs.org/api/built-in-directives.html#v-on). The `v-on` directive works via the `v-on:event="method"` syntax. And much like `v-bind`, there's also a shorthand syntax: `@event="method"`.
We'll use the shorthand syntax here for consistency. Add the `submit` handler to your `<form>` element like so:
```html
<form @submit="onSubmit">β¦</form>
```
3. When you run this, the app still posts the data to the server, causing a refresh. Since we're doing all of our processing on the client, there's no server to handle the postback. We also lose all local state on page refresh. To prevent the browser from posting to the server, we need to stop the event's default action while bubbling up through the page ([`Event.preventDefault()`](/en-US/docs/Web/API/Event/preventDefault), in vanilla JavaScript). Vue has a special syntax called **event modifiers** that can handle this for us right in our template.
Modifiers are appended to the end of an event with a dot like so: `@event.modifier`. Here is a list of event modifiers:
- `.stop`: Stops the event from propagating. Equivalent to [`Event.stopPropagation()`](/en-US/docs/Web/API/Event/stopPropagation) in regular JavaScript events.
- `.prevent`: Prevents the event's default behavior. Equivalent to [`Event.preventDefault()`](/en-US/docs/Web/API/Event/preventDefault).
- `.self`: Triggers the handler only if the event was dispatched from this exact element.
- `{.key}`: Triggers the event handler only via the specified key. [MDN has a list of valid key values](/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values); multi-word keys just need to be converted to {{Glossary("kebab_case", "kebab-case")}} (e.g. `page-down`).
- `.native`: Listens for a native event on the root (outer-most wrapping) element on your component.
- `.once`: Listens for the event until it's been triggered once, and then no more.
- `.left`: Only triggers the handler via the left mouse button event.
- `.right`: Only triggers the handler via the right mouse button event.
- `.middle`: Only triggers the handler via the middle mouse button event.
- `.passive`: Equivalent to using the `{ passive: true }` parameter when creating an event listener in vanilla JavaScript using [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener).
In this case, we need to use the `.prevent` modifier to stop the browser's default submit action. Add `.prevent` to the `@submit` handler in your template like so:
```html
<form @submit.prevent="onSubmit">β¦</form>
```
If you try submitting the form now, you'll notice that the page doesn't reload. If you open the console, you can see the results of the [`console.log()`](/en-US/docs/Web/API/console/log_static) we added inside our `onSubmit()` method.
## Binding data to inputs with v-model
Next up, we need a way to get the value from the form's `<input>` so we can add the new to-do item to our `ToDoItems` data list.
The first thing we need is a `data` property in our form to track the value of the to-do.
1. Add a `data()` method to our `ToDoForm` component object that returns a `label` field. We can set the initial value of the `label` to an empty string.
Your component object should now look something like this:
```js
export default {
methods: {
onSubmit() {
console.log("form submitted");
},
},
data() {
return {
label: "",
};
},
};
```
2. We now need some way to attach the value of the `new-todo-input` element's field to the `label` field. Vue has a special directive for this: [`v-model`](https://vuejs.org/api/built-in-directives.html#v-model). `v-model` binds to the data property you set on it and keeps it in sync with the `<input>`. `v-model` works across all the various input types, including checkboxes, radios, and select inputs. To use `v-model`, you add an attribute with the structure `v-model="variable"` to the `<input>`.
So in our case, we would add it to our `new-todo-input` field as seen below. Do this now:
```html
<input
type="text"
id="new-todo-input"
name="new-todo"
autocomplete="off"
v-model="label" />
```
> **Note:** You can also sync data with `<input>` values through a combination of events and `v-bind` attributes. In fact, this is what `v-model` does behind the scenes. However, the exact event and attribute combination varies depending on input types and will take more code than just using the `v-model` shortcut.
3. Let's test out our use of `v-model` by logging the value of the data submitted in our `onSubmit()` method. In components, data attributes are accessed using the `this` keyword. So we access our `label` field using `this.label`.
Update your `onSubmit()` method to look like this:
```js
methods: {
onSubmit() {
console.log('Label value: ', this.label);
}
},
```
4. Now go back to your running app, add some text to the `<input>` field, and click the "Add" button. You should see the value you entered logged to your console, for example:
```plain
Label value: My value
```
## Changing v-model behavior with modifiers
In a similar fashion to event modifiers, we can also add modifiers to change the behavior of `v-model`. In our case, there are two worth considering. The first, `.trim`, will remove whitespace from before or after the input. We can add the modifier to our `v-model` statement like so: `v-model.trim="label"`.
The second modifier we should consider is called `.lazy`. This modifier changes when `v-model` syncs the value for text inputs. As mentioned earlier, `v-model` syncing works by updating the variable using events. For text inputs, this sync happens using the [`input` event](/en-US/docs/Web/API/Element/input_event). Often, this means that Vue is syncing the data after every keystroke. The `.lazy` modifier causes `v-model` to use the [`change` event](/en-US/docs/Web/API/HTMLElement/change_event) instead. This means that Vue will only sync data when the input loses focus or the form is submitted. For our purposes, this is much more reasonable since we only need the final data.
To use both the `.lazy` modifier and the `.trim` modifier together, we can chain them, e.g. `v-model.lazy.trim="label"`.
Update your `v-model` attribute to chain `lazy` and `trim` as shown above, and then test your app again. Try for example, submitting a value with whitespace at each end.
## Passing data to parents with custom events
We now are very close to being able to add new to-do items to our list. The next thing we need to be able to do is pass the newly-created to-do item to our `App` component. To do that, we can have our `ToDoForm` emit a custom event that passes the data, and have `App` listen for it. This works very similarly to native events on HTML elements: a child component can emit an event which can be listened to via `v-on`.
In the `onSubmit` event handler of our `ToDoForm`, let's add a `todo-added` event. Custom events are emitted like this: `this.$emit("event-name")`. It's important to know that event handlers are case sensitive and cannot include spaces. Vue templates also get converted to lowercase, which means Vue templates cannot listen for events named with capital letters.
1. Replace the `console.log()` in the `onSubmit()` method with the following:
```js
this.$emit("todo-added");
```
2. Next, go back to `App.vue` and add a `methods` property to your component object containing an `addToDo()` method, as shown below. For now, this method can just log `To-do added` to the console.
```js
export default {
name: "app",
components: {
ToDoItem,
ToDoForm,
},
data() {
return {
ToDoItems: [
{ id: uniqueId("todo-"), label: "Learn Vue", done: false },
{
id: uniqueId("todo-"),
label: "Create a Vue project with the CLI",
done: true,
},
{ id: uniqueId("todo-"), label: "Have fun", done: true },
{ id: uniqueId("todo-"), label: "Create a to-do list", done: false },
],
};
},
methods: {
addToDo() {
console.log("To-do added");
},
},
};
```
3. Next, add an event listener for the `todo-added` event to the `<to-do-form></to-do-form>`, which calls the `addToDo()` method when the event fires. Using the `@` shorthand, the listener would look like this: `@todo-added="addToDo"`:
```html
<to-do-form @todo-added="addToDo"></to-do-form>
```
4. When you submit your `ToDoForm`, you should see the console log from the `addToDo()` method. This is good, but we're still not passing any data back into the `App.vue` component. We can do that by passing additional arguments to the `this.$emit()` function back in the `ToDoForm` component.
In this case, when we fire the event we want to pass the `label` data along with it. This is done by including the data you want to pass as another parameter in the `$emit()` method: `this.$emit("todo-added", this.label)`. This is similar to how native JavaScript events include data, except custom Vue events include no event object by default. This means that the emitted event will directly match whatever object you submit. So in our case, our event object will just be a string.
Update your `onSubmit()` method like so:
```js
onSubmit() {
this.$emit('todo-added', this.label)
}
```
5. To actually pick up this data inside `App.vue`, we need to add a parameter to our `addToDo()` method that includes the `label` of the new to-do item.
Go back to `App.vue` and update this now:
```js
methods: {
addToDo(toDoLabel) {
console.log('To-do added:', toDoLabel);
}
}
```
If you test your form again, you'll see whatever text you enter logged in your console upon submission. Vue automatically passes the arguments after the event name in `this.$emit()` to your event handler.
## Adding the new todo into our data
Now that we have the data from `ToDoForm` available in `App.vue`, we need to add an item representing it to the `ToDoItems` array. This can be done by pushing a new to-do item object to the array containing our new data.
1. Update your `addToDo()` method like so:
```js
addToDo(toDoLabel) {
this.ToDoItems.push({id:uniqueId('todo-'), label: toDoLabel, done: false});
}
```
2. Try testing your form again, and you should see new to-do items get appended to the end of the list.
3. Let's make a further improvement before we move on. If you submit the form while the input is empty, todo items with no text still get added to the list. To fix that, we can prevent the todo-added event from firing when name is empty. Since name is already being trimmed by the `.trim` modifier, we only need to test for the empty string.
Go back to your `ToDoForm` component, and update the `onSubmit()` method like so. If the label value is empty, let's not emit the `todo-added` event.
```js
onSubmit() {
if (this.label === "") {
return;
}
this.$emit('todo-added', this.label);
}
```
4. Try your form again. Now you will not be able to add empty items to the to-do list.

## Using v-model to update an input value
There's one more thing to fix in our `ToDoForm` component β after submitting, the `<input>` still contains the old value. But this is easy to fix β because we're using `v-model` to bind the data to the `<input>` in `ToDoForm`, if we set the name parameter to equal an empty string, the input will update as well.
Update your `ToDoForm` component's `onSubmit()` method to this:
```js
onSubmit() {
if (this.label === "") {
return;
}
this.$emit('todo-added', this.label);
this.label = "";
}
```
Now when you click the "Add" button, the "new-todo-input" will clear itself.
## Summary
Excellent. We can now add todo items to our form! Our app is now starting to feel interactive, but one issue is that we've completely ignored its look and feel up to now. In the next article, we'll concentrate on fixing this, looking at the different ways Vue provides to style components.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_rendering_lists","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/vue_refs_focus_management/index.md | ---
title: Vue refs and lifecycle methods for focus management
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_refs_focus_management
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
We are nearly done with Vue. The last bit of functionality to look at is focus management, or put another way, how we can improve our app's keyboard accessibility. We'll look at using **Vue refs** to handle this β an advanced feature that allows you to have direct access to the underlying DOM nodes below the virtual DOM, or direct access from one component to the internal DOM structure of a child component.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn how to handle focus management using Vue refs.</td>
</tr>
</tbody>
</table>
## The focus management problem
While we do have working edit functionality, we aren't providing a great experience for non-mouse users. Specifically, when a user activates the "Edit" button, we remove the "Edit" button from the DOM, but we don't move the user's focus anywhere, so in effect it just disappears. This can be disorienting for keyboard and non-visual users.
To understand what's currently happening:
1. Reload your page, then press <kbd>Tab</kbd>. You should see a focus outline on the input for adding new to-do items.
2. Press <kbd>Tab</kbd> again. The focus should move to the "Add" button.
3. Hit it again, and it'll be on the first checkbox. One more time, and focus should be on the first "Edit" button.
4. Activate the "Edit" button by pressing <kbd>Enter</kbd>.
The checkbox will be replaced with our edit component, but the focus outline will be gone.
This behavior can be jarring. In addition, what happens when you press <kbd>Tab</kbd> again varies depending on the browser you're using. Similarly, if you save or cancel your edit, focus will disappear again as you move back to the non-edit view.
To give users a better experience, we'll add code to control the focus so that it gets set to the edit field when the edit form is shown. We'll also want to put focus back on the "Edit" button when a user cancels or saves their edit. In order to set focus, we need to understand a little bit more about how Vue works internally.
## Virtual DOM and refs
Vue, like some other frameworks, uses a virtual DOM (VDOM) to manage elements. This means that Vue keeps a representation of all of the nodes in our app in memory. Any updates are first performed on the in-memory nodes, and then all the changes that need to be made to the actual nodes on the page are synced in a batch.
Since reading and writing actual DOM nodes is often more expensive than virtual nodes, this can result in better performance. However, it also means you often should not edit your HTML elements directly through native browser APIs (like [`Document.getElementById`](/en-US/docs/Web/API/Document/getElementById)) when using frameworks, because it results in the VDOM and real DOM going out of sync.
Instead, if you need to access the underlying DOM nodes (like when setting focus), you can use [Vue refs](https://vuejs.org/guide/essentials/template-refs.html). For custom Vue components, you can also use refs to directly access the internal structure of a child component, however this should be done with caution as it can make code harder to reason about and understand.
To use a ref in a component, you add a `ref` attribute to the element that you want to access, with a string identifier for the value of the attribute. It's important to note that a ref needs to be unique within a component. No two elements rendered at the same time should have the same ref.
### Adding a ref to our app
So, let's attach a ref to our "Edit" button in `ToDoItem.vue`. Update it like this:
```html
<button
type="button"
class="btn"
ref="editButton"
@click="toggleToItemEditForm">
Edit
<span class="visually-hidden">\{{label}}</span>
</button>
```
To access the value associated with our ref, we use the `$refs` property provided on our component instance. To see the value of the ref when we click our "Edit" button, add a `console.log()` to our `toggleToItemEditForm()` method, like so:
```js
toggleToItemEditForm() {
console.log(this.$refs.editButton);
this.isEditing = true;
}
```
If you activate the "Edit" button at this point, you should see an HTML `<button>` element referenced in your console.
## Vue's $nextTick() method
We want to set focus on the "Edit" button when a user saves or cancels their edit. To do that, we need to handle focus in the `ToDoItem` component's `itemEdited()` and `editCancelled()` methods.
For convenience, create a new method which takes no arguments called `focusOnEditButton()`. Inside it, assign your `ref` to a variable, and then call the `focus()` method on the ref.
```js
focusOnEditButton() {
const editButtonRef = this.$refs.editButton;
editButtonRef.focus();
}
```
Next, add a call to `this.focusOnEditButton()` at the end of the `itemEdited()` and `editCancelled()` methods:
```js
itemEdited(newItemName) {
this.$emit("item-edited", newItemName);
this.isEditing = false;
this.focusOnEditButton();
},
editCancelled() {
this.isEditing = false;
this.focusOnEditButton();
},
```
Try editing and then saving/cancelling a to-do item via your keyboard. You'll notice that focus isn't being set, so we still have a problem to solve. If you open your console, you'll see an error raised along the lines of _"can't access property "focus", editButtonRef is undefined"_. This seems weird. Your button ref was defined when you activated the "Edit" button, but now it's not. What is going on?
Well, remember that when we change `isEditing` to `true`, we no longer render the section of the component featuring the "Edit" button. This means there's no element to bind the ref to, so it becomes `undefined`.
You might now be thinking "hey, don't we set `isEditing=false` before we try to access the `ref`, so therefore shouldn't the `v-if` now be displaying the button?" This is where the virtual DOM comes into play. Because Vue is trying to optimize and batch changes, it won't immediately update the DOM when we set `isEditing` to `false`. So when we call `focusOnEditButton()`, the "Edit" button has not been rendered yet.
Instead, we need to wait until after Vue undergoes the next DOM update cycle. To do that, Vue components have a special method called `$nextTick()`. This method accepts a callback function, which then executes after the DOM updates.
Since the `focusOnEditButton()` method needs to be invoked after the DOM has updated, we can wrap the existing function body inside a `$nextTick()` call.
```js
focusOnEditButton() {
this.$nextTick(() => {
const editButtonRef = this.$refs.editButton;
editButtonRef.focus();
});
}
```
Now when you activate the "Edit" button and then cancel or save your changes via the keyboard, focus should be returned to the "Edit" button. Success!
## Vue lifecycle methods
Next, we need to move focus to the edit form's `<input>` element when the "Edit" button is clicked. However, because our edit form is in a different component to our "Edit" button, we can't just set focus inside the "Edit" button's click event handler. Instead, we can use the fact that we remove and re-mount our `ToDoItemEditForm` component whenever the "Edit" button is clicked to handle this.
So how does this work? Well, Vue components undergo a series of events, known as a **lifecycle**. This lifecycle spans from all the way before elements are _created_ and added to the VDOM (_mounted_), until they are removed from the VDOM (_destroyed_).
Vue lets you run methods at various stages of this lifecycle using **lifecycle methods**. This can be useful for things like data fetching, where you may need to get your data before your component renders, or after a property changes. The list of lifecycle methods are below, in the order that they fire.
1. `beforeCreate()` β Runs before the instance of your component is created. Data and events are not yet available.
2. `created()` β Runs after your component is initialized but before the component is added to the VDOM. This is often where data fetching occurs.
3. `beforeMount()` β Runs after your template is compiled, but before your component is rendered to the actual DOM.
4. `mounted()` β Runs after your component is mounted to the DOM. Can access `refs` here.
5. `beforeUpdate()` β Runs whenever data in your component changes, but before the changes are rendered to the DOM.
6. `updated()` β Runs whenever data in your component has changed and after the changes are rendered to the DOM.
7. `beforeDestroy()` β Runs before a component is removed from the DOM.
8. `destroyed()` β Runs after a component has been removed from the DOM.
9. `activated()` β Only used in components wrapped in a special `keep-alive` tag. Runs after the component is activated.
10. `deactivated()` β Only used in components wrapped in a special `keep-alive` tag. Runs after the component is deactivated.
> **Note:** The Vue Docs provide a [nice diagram for visualizing when these hooks happen](https://vuejs.org/guide/essentials/lifecycle.html#lifecycle-diagram). This article from the [Digital Ocean Community Blog dives into the lifecycle methods more deeply](https://www.digitalocean.com/community/tutorials/vuejs-component-lifecycle).
Now that we've gone over the lifecycle methods, let's use one to trigger focus when our `ToDoItemEditForm` component is mounted.
In `ToDoItemEditForm.vue`, attach `ref="labelInput"` to the `<input>` element, like so:
```html
<input
:id="id"
ref="labelInput"
type="text"
autocomplete="off"
v-model.lazy.trim="newName" />
```
Next, add a `mounted()` property just inside your component object β **note that this should not be put inside the `methods` property, but rather at the same hierarchy level as `props`, `data()`, and `methods`.** Lifecycle methods are special methods that sit on their own, not alongside the user-defined methods. This should take no inputs. Note that you cannot use an arrow function here since we need access to `this` to access our `labelInput` ref.
```js
mounted() {
}
```
Inside your `mounted()` method, assign your `labelInput` ref to a variable, and then call the `focus()` function of the ref. You don't have to use `$nextTick()` here because the component has already been added to the DOM when `mounted()` is called.
```js
mounted() {
const labelInputRef = this.$refs.labelInput;
labelInputRef.focus();
}
```
Now when you activate the "Edit" button with your keyboard, focus should immediately be moved to the edit `<input>`.
## Handling focus when deleting to-do items
There's one more place we need to consider focus management: when a user deletes a to-do. When clicking the "Edit" button, it makes sense to move focus to the edit name text box, and back to the "Edit" button when canceling or saving from the edit screen.
However, unlike with the edit form, we don't have a clear location for focus to move to when an element is deleted. We also need a way to provide assistive technology users with information that confirms that an element was deleted.
We're already tracking the number of elements in our list heading β the `<h2>` in `App.vue` β and it's associated with our list of to-do items. This makes it a reasonable place to move focus to when we delete a node.
First, we need to add a ref to our list heading. We also need to add a `tabindex="-1"` to it β this makes the element programmatically focusable (i.e. it can be focused via JavaScript), when by default it is not.
Inside `App.vue`, update your `<h2>` as follows:
```html
<h2 id="list-summary" ref="listSummary" tabindex="-1">\{{listSummary}}</h2>
```
> **Note:** [`tabindex`](/en-US/docs/Web/HTML/Global_attributes/tabindex) is a really powerful tool for handling certain accessibility problems. However, it should be used with caution. Over-using `tabindex="-1"` can cause problems for all sorts of users, so only use it exactly where you need to. You should also almost never use `tabindex` > = `0`, as it can cause problems for users since it can make the DOM flow and the tab-order mismatch, and/or add non-interactive elements to the tab order. This can be confusing to users, especially those using screen readers and other assistive technology.
Now that we have a `ref` and have let browsers know that we can programmatically focus the `<h2>`, we need to set focus on it. At the end of `deleteToDo()`, use the `listSummary` ref to set focus on the `<h2>`. Since the `<h2>` is always rendered in the app, you do not need to worry about using `$nextTick()` or lifecycle methods to handle focusing it.
```js
deleteToDo(toDoId) {
const itemIndex = this.ToDoItems.findIndex((item) => item.id === toDoId);
this.ToDoItems.splice(itemIndex, 1);
this.$refs.listSummary.focus();
}
```
Now, when you delete an item from your list, focus should be moved up to the list heading. This should provide a reasonable focus experience for all of our users.
## Summary
So that's it for focus management, and for our app! Congratulations for working your way through all our Vue tutorials. In the next article we'll round things off with some further resources to take your Vue learning further.
> **Note:** If you need to check your code against our version, you can find a finished version of the sample Vue app code in our todo-vue repository. For a running live version, see <https://mdn.github.io/todo-vue/>.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_conditional_rendering","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/vue_styling/index.md | ---
title: Styling Vue components with CSS
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_styling
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
The time has finally come to make our app look a bit nicer. In this article we'll explore the different ways of styling Vue components with CSS.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages,
knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
Vue components are written as a combination of JavaScript objects that
manage the app's data and an HTML-based template syntax that maps to
the underlying DOM structure. For installation, and to use some of the
more advanced features of Vue (like Single File Components or render
functions), you'll need a terminal with node + npm installed.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>To learn about styling Vue components.</td>
</tr>
</tbody>
</table>
## Styling Vue components with CSS
Before we move on to add more advanced features to our app, we should add some basic CSS to make it look better. Vue has three common approaches to styling apps:
- External CSS files.
- Global styles in Single File Components (`.vue` files).
- Component-scoped styles in Single File Components.
To help familiarize you with each one, we'll use a combination of all three to give our app a nicer look and feel.
## Styling with external CSS files
You can include external CSS files and apply them globally to your app. Let's look at how this is done.
To start with, create a file called `reset.css` in the `src/assets` directory. Files in this folder get processed by Webpack. This means we can use CSS pre-processors (like SCSS) or post-processors (like PostCSS).
While this tutorial will not be using such tools, it's good to know that when including such code in the assets folder it will be processed automatically.
Add the following contents to the `reset.css` file:
```css
/*reset.css*/
/* RESETS */
*,
*::before,
*::after {
box-sizing: border-box;
}
*:focus {
outline: 3px dashed #228bec;
}
html {
font: 62.5% / 1.15 sans-serif;
}
h1,
h2 {
margin-bottom: 0;
}
ul {
list-style: none;
padding: 0;
}
button {
border: none;
margin: 0;
padding: 0;
width: auto;
overflow: visible;
background: transparent;
color: inherit;
font: inherit;
line-height: normal;
-webkit-font-smoothing: inherit;
-moz-osx-font-smoothing: inherit;
appearance: none;
}
button::-moz-focus-inner {
border: 0;
}
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
font-size: 100%;
line-height: 1.15;
margin: 0;
}
button,
input {
/* 1 */
overflow: visible;
}
input[type="text"] {
border-radius: 0;
}
body {
width: 100%;
max-width: 68rem;
margin: 0 auto;
font:
1.6rem/1.25 "Helvetica Neue",
Helvetica,
Arial,
sans-serif;
background-color: #f5f5f5;
color: #4d4d4d;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
}
@media screen and (min-width: 620px) {
body {
font-size: 1.9rem;
line-height: 1.31579;
}
}
/*END RESETS*/
```
Next, in your `src/main.js` file, import the `reset.css` file like so:
```js
import "./assets/reset.css";
```
This will cause the file to get picked up during the build step and automatically added to our site.
The reset styles should be applied to the app now. The images below show the look of the app before and after the reset is applied.
Before:

After:

Noticeable changes include the removal of the list bullets, background color changes, and changes to the base button and input styles.
## Adding global styles to Single File Components
Now that we've reset our CSS to be uniform across browsers, we need to customize the styles a bit more. There are some styles that we want to apply across components in our app. While adding these files directly to the `reset.css` stylesheet would work, we'll instead add them to the `<style>` tags in `App.vue` to demonstrate how this can be used.
There are already some styles present in the file. Let's remove those and replace them with the styles below. These styles do a few things β adding some styling to buttons and inputs, and customizing the `#app` element and its children.
Update your `App.vue` file's `<style>` element so it looks like so:
```html
<style>
/* Global styles */
.btn {
padding: 0.8rem 1rem 0.7rem;
border: 0.2rem solid #4d4d4d;
cursor: pointer;
text-transform: capitalize;
}
.btn__danger {
color: #fff;
background-color: #ca3c3c;
border-color: #bd2130;
}
.btn__filter {
border-color: lightgrey;
}
.btn__danger:focus {
outline-color: #c82333;
}
.btn__primary {
color: #fff;
background-color: #000;
}
.btn-group {
display: flex;
justify-content: space-between;
}
.btn-group > * {
flex: 1 1 auto;
}
.btn-group > * + * {
margin-left: 0.8rem;
}
.label-wrapper {
margin: 0;
flex: 0 0 100%;
text-align: center;
}
[class*="__lg"] {
display: inline-block;
width: 100%;
font-size: 1.9rem;
}
[class*="__lg"]:not(:last-child) {
margin-bottom: 1rem;
}
@media screen and (min-width: 620px) {
[class*="__lg"] {
font-size: 2.4rem;
}
}
.visually-hidden {
position: absolute;
height: 1px;
width: 1px;
overflow: hidden;
clip: rect(1px 1px 1px 1px);
clip: rect(1px, 1px, 1px, 1px);
clip-path: rect(1px, 1px, 1px, 1px);
white-space: nowrap;
}
[class*="stack"] > * {
margin-top: 0;
margin-bottom: 0;
}
.stack-small > * + * {
margin-top: 1.25rem;
}
.stack-large > * + * {
margin-top: 2.5rem;
}
@media screen and (min-width: 550px) {
.stack-small > * + * {
margin-top: 1.4rem;
}
.stack-large > * + * {
margin-top: 2.8rem;
}
}
/* End global styles */
#app {
background: #fff;
margin: 2rem 0 4rem 0;
padding: 1rem;
padding-top: 0;
position: relative;
box-shadow:
0 2px 4px 0 rgb(0 0 0 / 20%),
0 2.5rem 5rem 0 rgb(0 0 0 / 10%);
}
@media screen and (min-width: 550px) {
#app {
padding: 4rem;
}
}
#app > * {
max-width: 50rem;
margin-left: auto;
margin-right: auto;
}
#app > form {
max-width: 100%;
}
#app h1 {
display: block;
min-width: 100%;
width: 100%;
text-align: center;
margin: 0;
margin-bottom: 1rem;
}
</style>
```
If you check the app, you'll see that our todo list is now in a card, and we have some better formatting of our to-do items. Now we can go through and begin editing our components to use some of these styles.

### Adding CSS classes in Vue
We should apply the button CSS classes to the `<button>` in our `ToDoForm` component. Since Vue templates are valid HTML, this is done in the same way to how you might do it in plain HTML β by adding a `class=""` attribute to the element.
Add `class="btn btn__primary btn__lg"` to your form's `<button>` element:
```html
<button type="submit" class="btn btn__primary btn__lg">Add</button>
```
While we're here, there's one more semantic and styling change we can make. Since our form denotes a specific section of our page, it could benefit from an `<h2>` element. The label, however, already denotes the purpose of the form. To avoid repeating ourselves, let's wrap our label in an `<h2>`. There are a few other global CSS styles which we can add as well. We'll also add the `input__lg` class to our `<input>` element.
Update your `ToDoForm` template so that it looks like this:
```html
<template>
<form @submit.prevent="onSubmit">
<h2 class="label-wrapper">
<label for="new-todo-input" class="label__lg">
What needs to be done?
</label>
</h2>
<input
type="text"
id="new-todo-input"
name="new-todo"
autocomplete="off"
v-model.lazy.trim="label"
class="input__lg" />
<button type="submit" class="btn btn__primary btn__lg">Add</button>
</form>
</template>
```
Let's also add the `stack-large` class to the `<ul>` tag in our `App.vue` file. This will help improve the spacing of our to-do items a bit.
Update it as follows:
```html
<ul aria-labelledby="list-summary" class="stack-large">
β¦
</ul>
```
## Adding scoped styles
The last component we want to style is our `ToDoItem` component. To keep the style definitions close to the component we can add a `<style>` element inside it. However, if these styles alter things outside of this component, it could be challenging to track down the styles responsible, and fix the problem. This is where the `scoped` attribute can be useful β this attaches a unique HTML `data` attribute selector to all of your styles, preventing them from colliding globally.
To use the `scoped` modifier, create a `<style>` element inside `ToDoItem.vue`, at the bottom of the file, and give it a `scoped` attribute:
```html
<style scoped>
/* β¦ */
</style>
```
Next, copy the following CSS into the newly created `<style>` element:
```css
.custom-checkbox > .checkbox-label {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
color: #0b0c0c;
display: block;
margin-bottom: 5px;
}
.custom-checkbox > .checkbox {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
font-size: 16px;
font-size: 1rem;
line-height: 1.25;
box-sizing: border-box;
width: 100%;
height: 40px;
height: 2.5rem;
margin-top: 0;
padding: 5px;
border: 2px solid #0b0c0c;
border-radius: 0;
appearance: none;
}
.custom-checkbox > input:focus {
outline: 3px dashed #fd0;
outline-offset: 0;
box-shadow: inset 0 0 0 2px;
}
.custom-checkbox {
font-family: Arial, sans-serif;
-webkit-font-smoothing: antialiased;
font-weight: 400;
font-size: 1.6rem;
line-height: 1.25;
display: block;
position: relative;
min-height: 40px;
margin-bottom: 10px;
padding-left: 40px;
clear: left;
}
.custom-checkbox > input[type="checkbox"] {
-webkit-font-smoothing: antialiased;
cursor: pointer;
position: absolute;
z-index: 1;
top: -2px;
left: -2px;
width: 44px;
height: 44px;
margin: 0;
opacity: 0;
}
.custom-checkbox > .checkbox-label {
font-size: inherit;
font-family: inherit;
line-height: inherit;
display: inline-block;
margin-bottom: 0;
padding: 8px 15px 5px;
cursor: pointer;
touch-action: manipulation;
}
.custom-checkbox > label::before {
content: "";
box-sizing: border-box;
position: absolute;
top: 0;
left: 0;
width: 40px;
height: 40px;
border: 2px solid currentcolor;
background: transparent;
}
.custom-checkbox > input[type="checkbox"]:focus + label::before {
border-width: 4px;
outline: 3px dashed #228bec;
}
.custom-checkbox > label::after {
box-sizing: content-box;
content: "";
position: absolute;
top: 11px;
left: 9px;
width: 18px;
height: 7px;
transform: rotate(-45deg);
border: solid;
border-width: 0 0 5px 5px;
border-top-color: transparent;
opacity: 0;
background: transparent;
}
.custom-checkbox > input[type="checkbox"]:checked + label::after {
opacity: 1;
}
@media only screen and (min-width: 40rem) {
label,
input,
.custom-checkbox {
font-size: 19px;
font-size: 1.9rem;
line-height: 1.31579;
}
}
```
Now we need to add some CSS classes to our template to connect the styles.
To the root `<div>`, add a `custom-checkbox` class. To the `<input>`, add a `checkbox` class. Last of all, to the `<label>` add a `checkbox-label` class. The updated template is below:
```html
<template>
<div class="custom-checkbox">
<input type="checkbox" :id="id" :checked="isDone" class="checkbox" />
<label :for="id" class="checkbox-label">\{{label}}</label>
</div>
</template>
```
The app should now have custom checkboxes. Your app should look something like the screenshot below.

## Summary
Our work is done on the styling of our sample app. In the next article we'll return to adding some more functionality to our app, namely using a computed property to add a count of completed todo items to our app.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_methods_events_models","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_computed_properties", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/svelte_reactivity_lifecycle_accessibility/index.md | ---
title: "Advanced Svelte: Reactivity, lifecycle, accessibility"
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_reactivity_lifecycle_accessibility
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
In the last article we added more features to our to-do list and started to organize our app into components. In this article we will add the app's final features and further componentize our app. We will learn how to deal with reactivity issues related to updating objects and arrays. To avoid common pitfalls, we'll have to dig a little deeper into Svelte's reactivity system. We'll also look at solving some accessibility focus issues, and more besides.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
You'll need a terminal with node and npm installed to compile and build
your app.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
Learn some advanced Svelte techniques involving solving reactivity
issues, keyboard accessibility problems to do with component lifecycle,
and more.
</td>
</tr>
</tbody>
</table>
We'll focus on some accessibility issues involving focus management. To do so, we'll utilize some techniques for accessing DOM nodes and executing methods like [`focus()`](/en-US/docs/Web/API/HTMLElement/focus) and [`select()`](/en-US/docs/Web/API/HTMLInputElement/select). We will also see how to declare and clean up event listeners on DOM elements.
We also need to learn a bit about component lifecycle to understand when these DOM nodes get mounted and unmounted from the DOM and how we can access them. We will also learn about the `action` directive, which will allow us to extend the functionality of HTML elements in a reusable and declarative way.
Finally, we will learn a bit more about components. So far, we've seen how components can share data using props, and communicate with their parents using events and two-way data binding. Now we will see how components can also expose methods and variables.
The following new components will be developed throughout the course of this article:
- `MoreActions`: Displays the _Check All_ and _Remove Completed_ buttons, and emits the corresponding events required to handle their functionality.
- `NewTodo`: Displays the `<input>` field and _Add_ button for adding a new to-do.
- `TodosStatus`: Displays the "x out of y items completed" status heading.
## Code along with us
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/05-advanced-concepts
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/05-advanced-concepts
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To code along with us using the REPL, start at
<https://svelte.dev/repl/76cc90c43a37452e8c7f70521f88b698?version=3.23.2>
## Working on the MoreActions component
Now we'll tackle the _Check All_ and _Remove Completed_ buttons. Let's create a component that will be in charge of displaying the buttons and emitting the corresponding events.
1. Create a new file, `components/MoreActions.svelte`.
2. When the first button is clicked, we'll emit a `checkAll` event to signal that all the to-dos should be checked/unchecked. When the second button is clicked, we'll emit a `removeCompleted` event to signal that all of the completed to-dos should be removed. Put the following content into your `MoreActions.svelte` file:
```svelte
<script>
import { createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
let completed = true;
const checkAll = () => {
dispatch("checkAll", completed);
completed = !completed;
};
const removeCompleted = () => dispatch("removeCompleted");
</script>
<div class="btn-group">
<button type="button" class="btn btn__primary" on:click={checkAll}>{completed ? 'Check' : 'Uncheck'} all</button>
<button type="button" class="btn btn__primary" on:click={removeCompleted}>Remove completed</button>
</div>
```
We've also included a `completed` variable to toggle between checking and unchecking all tasks.
3. Back over in `Todos.svelte`, we are going to import our `MoreActions` component and create two functions to handle the events emitted by the `MoreActions` component.
Add the following import statement below the existing ones:
```js
import MoreActions from "./MoreActions.svelte";
```
4. Then add the described functions at the end of the `<script>` section:
```js
const checkAllTodos = (completed) =>
todos.forEach((t) => (t.completed = completed));
const removeCompletedTodos = () =>
(todos = todos.filter((t) => !t.completed));
```
5. Now go to the bottom of the `Todos.svelte` markup section and replace the `<div class="btn-group">` element that we copied into `MoreActions.svelte` with a call to the `MoreActions` component, like so:
```svelte
<!-- MoreActions -->
<MoreActions
on:checkAll={(e) => checkAllTodos(e.detail)}
on:removeCompleted={removeCompletedTodos}
/>
```
6. OK, let's go back into the app and try it out. You'll find that the _Remove Completed_ button works fine, but the _Check All_/_Uncheck All_ button just silently fails.
To find out what is happening here, we'll have to dig a little deeper into Svelte reactivity.
## Reactivity gotchas: updating objects and arrays
To see what's happening we can log the `todos` array from the `checkAllTodos()` function to the console.
1. Update your existing `checkAllTodos()` function to the following:
```js
const checkAllTodos = (completed) => {
todos.forEach((t) => (t.completed = completed));
console.log("todos", todos);
};
```
2. Go back to your browser, open your DevTools console, and click _Check All_/_Uncheck All_ a few times.
You'll notice that the array is successfully updated every time you press the button (the `todo` objects' `completed` properties are toggled between `true` and `false`), but Svelte is not aware of that. This also means that in this case, a reactive statement like `$: console.log('todos', todos)` won't be very useful.
To find out why this is happening, we need to understand how reactivity works in Svelte when updating arrays and objects.
Many web frameworks use the virtual DOM technique to update the page. Basically, the virtual DOM is an in-memory copy of the contents of the web page. The framework updates this virtual representation, which is then synced with the "real" DOM. This is much faster than directly updating the DOM and allows the framework to apply many optimization techniques.
These frameworks, by default, basically re-run all our JavaScript on every change against this virtual DOM, and apply different methods to cache expensive calculations and optimize execution. They make little to no attempt to understand what our JavaScript code is doing.
Svelte doesn't use a virtual DOM representation. Instead, it parses and analyzes our code, creates a dependency tree, and then generates the required JavaScript to update only the parts of the DOM that need to be updated. This approach usually generates optimal JavaScript code with minimal overhead, but it also has its limitations.
Sometimes Svelte cannot detect changes to variables being watched. Remember that to tell Svelte that a variable has changed, you have to assign it a new value. A simple rule to keep in mind is that **The name of the updated variable must appear on the left-hand side of the assignment.**
For example, in the following piece of code:
```js
const foo = obj.foo;
foo.bar = "baz";
```
Svelte won't update references to `obj.foo.bar`, unless you follow it up with `obj = obj`. That's because Svelte can't track object references, so we have to explicitly tell it that `obj` has changed by issuing an assignment.
> **Note:** If `foo` is a top-level variable, you can easily tell Svelte to update `obj` whenever `foo` is changed with the following reactive statement: `$: foo, obj = obj`. With this we are defining `foo` as a dependency, and whenever it changes Svelte will run `obj = obj`.
In our `checkAllTodos()` function, when we run:
```js
todos.forEach((t) => (t.completed = completed));
```
Svelte will not mark `todos` as changed because it does not know that when we update our `t` variable inside the `forEach()` method, we are also modifying the `todos` array. And that makes sense, because otherwise Svelte would be aware of the inner workings of the `forEach()` method; the same would therefore be true for any method attached to any object or array.
Nevertheless, there are different techniques that we can apply to solve this problem, and all of them involve assigning a new value to the variable being watched.
As we already saw, we could just tell Svelte to update the variable with a self-assignment, like this:
```js
const checkAllTodos = (completed) => {
todos.forEach((t) => (t.completed = completed));
todos = todos;
};
```
This will solve the problem. Internally Svelte will flag `todos` as changed and remove the apparently redundant self-assignment. Apart from the fact that it looks weird, it's perfectly OK to use this technique, and sometimes it's the most concise way to do it.
We could also access the `todos` array by index, like this:
```js
const checkAllTodos = (completed) => {
todos.forEach((t, i) => (todos[i].completed = completed));
};
```
Assignments to properties of arrays and objects β e.g. `obj.foo += 1` or `array[i] = x` β work the same way as assignments to the values themselves. When Svelte analyzes this code, it can detect that the `todos` array is being modified.
Another solution is to assign a new array to `todos` containing a copy of all the to-dos with the `completed` property updated accordingly, like this:
```js
const checkAllTodos = (completed) => {
todos = todos.map((t) => ({ ...t, completed }));
};
```
In this case we are using the [`map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) method, which returns a new array with the results of executing the provided function for each item. The function returns a copy of each to-do using [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and overwrites the property of the completed value accordingly. This solution has the added benefit of returning a new array with new objects, completely avoiding mutating the original `todos` array.
> **Note:** Svelte allows us to specify different options that affect how the compiler works. The `<svelte:options immutable={true}/>` option tells the compiler that you promise not to mutate any objects. This allows it to be less conservative about checking whether values have changed and generate simpler and more performant code. For more information on `<svelte:options>`, check the [Svelte options documentation](https://svelte.dev/docs/special-elements#svelte-options).
All of these solutions involve an assignment in which the updated variable is on the left side of the equation. Any of this techniques will allow Svelte to notice that our `todos` array has been modified.
**Choose one, and update your `checkAllTodos()` function as required. Now you should be able to check and uncheck all your to-dos at once. Try it!**
## Finishing our MoreActions component
We will add one usability detail to our component. We'll disable the buttons when there are no tasks to be processed. To create this, we'll receive the `todos` array as a prop, and set the `disabled` property of each button accordingly.
1. Update your `MoreActions.svelte` component like this:
```svelte
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let todos;
let completed = true;
const checkAll = () => {
dispatch('checkAll', completed);
completed = !completed;
}
const removeCompleted = () => dispatch('removeCompleted');
$: completedTodos = todos.filter((t) => t.completed).length;
</script>
<div class="btn-group">
<button type="button" class="btn btn__primary"
disabled={todos.length === 0} on:click={checkAll}>{completed ? 'Check' : 'Uncheck'} all</button>
<button type="button" class="btn btn__primary"
disabled={completedTodos === 0} on:click={removeCompleted}>Remove completed</button>
</div>
```
We've also declared a reactive `completedTodos` variable to enable or disable the _Remove Completed_ button.
2. Don't forget to pass the prop into `MoreActions` from inside `Todos.svelte`, where the component is called:
```svelte
<MoreActions {todos}
on:checkAll={(e) => checkAllTodos(e.detail)}
on:removeCompleted={removeCompletedTodos}
/>
```
## Working with the DOM: focusing on the details
Now that we have completed all of the app's required functionality, we'll concentrate on some accessibility features that will improve the usability of our app for both keyboard-only and screen reader users.
In its current state our app has a couple of keyboard accessibility problems involving focus management. Let's have a look at these issues.
## Exploring keyboard accessibility issues in our to-do app
Right now, keyboard users will find out that the focus flow of our app is not very predictable or coherent.
If you click on the input at the top of our app, you'll see a thick, dashed outline around that input. This outline is your visual indicator that the browser is currently focused on this element.
If you are a mouse user, you might have skipped this visual hint. But if you are working exclusively with the keyboard, knowing which control has focus is of vital importance. It tells us which control is going to receive our keystrokes.
If you press the <kbd>Tab</kbd> key repeatedly, you'll see the dashed focus indicator cycling between all the focusable elements on the page. If you move the focus to the _Edit_ button and press <kbd>Enter</kbd>, suddenly the focus disappears, and you can no longer tell which control will receive our keystrokes.
Moreover, if you press the <kbd>Escape</kbd> or <kbd>Enter</kbd> key, nothing happens. And if you click on _Cancel_ or _Save_, the focus disappears again. For a user working with the keyboard, this behavior will be confusing at best.
We'd also like to add some usability features, like disabling the _Save_ button when required fields are empty, giving focus to certain HTML elements or auto-selecting contents when a text input receives focus.
To implement all these features, we'll need programmatic access to DOM nodes to run functions like [`focus()`](/en-US/docs/Web/API/HTMLElement/focus) and [`select()`](/en-US/docs/Web/API/HTMLInputElement/select). We will also have to use [`addEventListener()`](/en-US/docs/Web/API/EventTarget/addEventListener) and [`removeEventListener()`](/en-US/docs/Web/API/EventTarget/removeEventListener) to run specific tasks when the control receives focus.
The problem is that all these DOM nodes are dynamically created by Svelte at runtime. So we'll have to wait for them to be created and added to the DOM in order to use them. To do so, we'll have to learn about the [component lifecycle](https://learn.svelte.dev/tutorial/onmount) to understand when we can access them β more on this later.
## Creating a NewTodo component
Let's begin by extracting our new to-do form out to its own component. With what we know so far we can create a new component file and adjust the code to emit an `addTodo` event, passing the name of the new to-do in with the additional details.
1. Create a new file, `components/NewTodo.svelte`.
2. Put the following contents inside it:
```svelte
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
let name = '';
const addTodo = () => {
dispatch('addTodo', name);
name = '';
}
const onCancel = () => name = '';
</script>
<form on:submit|preventDefault={addTodo} on:keydown={(e) => e.key === 'Escape' && onCancel()}>
<h2 class="label-wrapper">
<label for="todo-0" class="label__lg">What needs to be done?</label>
</h2>
<input bind:value={name} type="text" id="todo-0" autoComplete="off" class="input input__lg" />
<button type="submit" disabled={!name} class="btn btn__primary btn__lg">Add</button>
</form>
```
Here we are binding the `<input>` to the `name` variable with `bind:value={name}` and disabling the _Add_ button when it is empty (i.e. no text content) using `disabled={!name}`. We are also taking care of the <kbd>Escape</kbd> key with `on:keydown={(e) => e.key === 'Escape' && onCancel()}`. Whenever the <kbd>Escape</kbd> key is pressed we run `onCancel()`, which just clears up the `name` variable.
3. Now we have to `import` and use it from inside the `Todos` component, and update the `addTodo()` function to receive the name of the new todo.
Add the following `import` statement below the others inside `Todos.svelte`:
```js
import NewTodo from "./NewTodo.svelte";
```
4. And update the `addTodo()` function like so:
```js
function addTodo(name) {
todos = [...todos, { id: newTodoId, name, completed: false }];
}
```
`addTodo()` now receives the name of the new to-do directly, so we no longer need the `newTodoName` variable to give it its value. Our `NewTodo` component takes care of that.
> **Note:** The `{ name }` syntax is just a shorthand for `{ name: name }`. This one comes from JavaScript itself and has nothing to do with Svelte, besides providing some inspiration for Svelte's own shorthands.
5. Finally for this section, replace the NewTodo form markup with a call to `NewTodo` component, like so:
```svelte
<!-- NewTodo -->
<NewTodo on:addTodo={(e) => addTodo(e.detail)} />
```
## Working with DOM nodes using the `bind:this={dom_node}` directive
Now we want the `<input>`element of the `NewTodo` component to re-gain focus every time the _Add_ button is pressed. For that we'll need a reference to the DOM node of the input. Svelte provides a way to do this with the `bind:this={dom_node}` directive. When specified, as soon as the component is mounted and the DOM node is created, Svelte assigns a reference to the DOM node to the specified variable.
We'll create a `nameEl` variable and bind it to the input using `bind:this={nameEl}`. Then inside `addTodo()`, after adding the new to-do we will call `nameEl.focus()` to refocus the `<input>` again. We will do the same when the user presses the <kbd>Escape</kbd> key, with the `onCancel()` function.
Update the contents of `NewTodo.svelte` like so:
```svelte
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
let name = '';
let nameEl; // reference to the name input DOM node
const addTodo = () => {
dispatch('addTodo', name);
name = '';
nameEl.focus(); // give focus to the name input
}
const onCancel = () => {
name = '';
nameEl.focus(); // give focus to the name input
}
</script>
<form on:submit|preventDefault={addTodo} on:keydown={(e) => e.key === 'Escape' && onCancel()}>
<h2 class="label-wrapper">
<label for="todo-0" class="label__lg">What needs to be done?</label>
</h2>
<input bind:value={name} bind:this={nameEl} type="text" id="todo-0" autoComplete="off" class="input input__lg" />
<button type="submit" disabled={!name} class="btn btn__primary btn__lg">Add</button>
</form>
```
Try the app out: type a new to-do name in to the `<input>` field, press <kbd>tab</kbd> to give focus to the _Add_ button, and then hit <kbd>Enter</kbd> or <kbd>Escape</kbd> to see how the input recovers focus.
### Autofocusing our input
The next feature will add to our `NewTodo` component will be an `autofocus` prop, which will allow us to specify that we want the `<input>` field to be focused on page load.
1. Our first attempt is as follows: let's try adding the `autofocus` prop and just call `nameEl.focus()` from the `<script>` block. Update the first part of the `<script>` section of `NewTodo.svelte` (the first four lines) to look like this:
```svelte
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let autofocus = false;
let name = '';
let nameEl; // reference to the name input DOM node
if (autofocus) nameEl.focus();
```
2. Now go back to the `Todos` component and pass the `autofocus` prop into the `<NewTodo>` component call, like so:
```svelte
<!-- NewTodo -->
<NewTodo autofocus on:addTodo={(e) => addTodo(e.detail)} />
```
3. If you try your app out now, you'll see that the page is now blank, and in your DevTools web console you'll see an error along the lines of: `TypeError: nameEl is undefined`.
To understand what's happening here, let's talk some more about that [component lifecycle](https://learn.svelte.dev/tutorial/onmount) we mentioned earlier.
## Component lifecycle, and the `onMount()` function
When a component is instantiated, Svelte runs the initialization code (that is, the `<script>` section of the component). But at that moment, all the nodes that comprise the component are not attached to the DOM, in fact, they don't even exist.
So how can you know when the component has already been created and mounted on the DOM? The answer is that every component has a lifecycle that starts when it is created and ends when it is destroyed. There are a handful of functions that allow you to run code at key moments during that lifecycle.
The one you'll use most frequently is `onMount()`, which lets us run a callback as soon as the component has been mounted on the DOM. Let's give it a try and see what happens to the `nameEl` variable.
1. To start with, add the following line at the beginning of the `<script>` section of `NewTodo.svelte`:
```js
import { onMount } from "svelte";
```
2. And these lines at the end of it:
```js
console.log("initializing:", nameEl);
onMount(() => {
console.log("mounted:", nameEl);
});
```
3. Now remove the `if (autofocus) nameEl.focus()` line to avoid throwing the error we were seeing before.
4. The app will now work again, and you'll see the following in your console:
```plain
initializing: undefined
mounted: <input id="todo-0" class="input input__lg" type="text" autocomplete="off">
```
As you can see, while the component is initializing, `nameEl` is undefined, which makes sense because the `<input>` node doesn't even exist yet. After the component has been mounted, Svelte assigned a reference to the `<input>` DOM node to the `nameEl` variable, thanks to the `bind:this={nameEl} directive`.
5. To get the autofocus functionality working, replace the previous `console.log()`/`onMount()` block you added with this:
```js
onMount(() => autofocus && nameEl.focus()); // if autofocus is true, we run nameEl.focus()
```
6. Go to your app again, and you'll now see the `<input>` field is focused on page load.
> **Note:** You can have a look at the other [lifecycle functions in the Svelte docs](https://svelte.dev/docs/svelte), and you can see them in action in the [interactive tutorial](https://learn.svelte.dev/tutorial/onmount).
## Waiting for the DOM to be updated with the `tick()` function
Now we will take care of the `Todo` component's focus management details. First of all, we want a `Todo` component's edit `<input>` to receive focus when we enter editing mode by pressing its _Edit_ button. In the same fashion as we saw earlier, we'll create a `nameEl` variable inside `Todo.svelte` and call `nameEl.focus()` after setting the `editing` variable to `true`.
1. Open the file `components/Todo.svelte` and add a `nameEl` variable declaration just below your editing and name declarations:
```js
let nameEl; // reference to the name input DOM node
```
2. Now update your `onEdit()` function like so:
```js
function onEdit() {
editing = true; // enter editing mode
nameEl.focus(); // set focus to name input
}
```
3. And finally, bind `nameEl` to the `<input>` field by updating it like so:
```svelte
<input
bind:value={name}
bind:this={nameEl}
type="text"
id="todo-{todo.id}"
autocomplete="off"
class="todo-text" />
```
4. However, when you try the updated app, you'll get an error along the lines of "TypeError: nameEl is undefined" in the console when you press a to-do's _Edit_ button.
So, what is happening here? When you update a component's state in Svelte, it doesn't update the DOM immediately. Instead, it waits until the next microtask to see if there are any other changes that need to be applied, including in other components. Doing so avoids unnecessary work and allows the browser to batch things more effectively.
In this case, when `editing` is `false`, the edit `<input>` is not visible because it does not exist in the DOM. Inside the `onEdit()` function we set `editing = true` and immediately afterwards try to access the `nameEl` variable and execute `nameEl.focus()`. The problem here is that Svelte hasn't yet updated the DOM.
One way to solve this problem is to use [`setTimeout()`](/en-US/docs/Web/API/setTimeout) to delay the call to `nameEl.focus()` until the next event cycle, and give Svelte the opportunity to update the DOM.
Try this now:
```js
function onEdit() {
editing = true; // enter editing mode
setTimeout(() => nameEl.focus(), 0); // asynchronous call to set focus to name input
}
```
The above solution works, but it is rather inelegant. Svelte provides a better way to handle these cases. The [`tick()` function](https://learn.svelte.dev/tutorial/tick) returns a promise that resolves as soon as any pending state changes have been applied to the DOM (or immediately, if there are no pending state changes). Let's try it now.
1. First of all, import `tick` at the top of the `<script>` section alongside your existing import:
```js
import { tick } from "svelte";
```
2. Next, call `tick()` with [`await`](/en-US/docs/Web/JavaScript/Reference/Operators/await) from an [async function](/en-US/docs/Web/JavaScript/Reference/Statements/async_function); update `onEdit()` like so:
```js
async function onEdit() {
editing = true; // enter editing mode
await tick();
nameEl.focus();
}
```
3. If you try it now you'll see that everything works as expected.
> **Note:** To see another example using `tick()`, visit the [Svelte tutorial](https://learn.svelte.dev/tutorial/tick).
## Adding functionality to HTML elements with the `use:action` directive
Next up, we want the name `<input>` to automatically select all text on focus. Moreover, we want to develop this in such a way that it could be easily reused on any HTML `<input>` and applied in a declarative way. We will use this requirement as an excuse to show a very powerful feature that Svelte provides us to add functionality to regular HTML elements: [actions](https://svelte.dev/docs/svelte-action).
To select the text of a DOM input node, we have to call [`select()`](/en-US/docs/Web/API/HTMLInputElement/select). To get this function called whenever the node gets focused, we need an event listener along these lines:
```js
node.addEventListener("focus", (event) => node.select());
```
And, in order to avoid memory leaks, we should also call the [`removeEventListener()`](/en-US/docs/Web/API/EventTarget/removeEventListener) function when the node is destroyed.
> **Note:** All this is just standard WebAPI functionality; nothing here is specific to Svelte.
We could achieve all this in our `Todo` component whenever we add or remove the `<input>` from the DOM, but we would have to be very careful to add the event listener after the node has been added to the DOM, and remove the listener before the node is removed from the DOM. In addition, our solution would not be very reusable.
That's where Svelte actions come into play. Basically they let us run a function whenever an element has been added to the DOM, and after removal from the DOM.
In our immediate use case, we will define a function called `selectOnFocus()` that will receive a node as a parameter. The function will add an event listener to that node so that whenever it gets focused it will select the text. Then it will return an object with a `destroy` property. The `destroy` property is what Svelte will execute after removing the node from the DOM. Here we will remove the listener to make sure we don't leave any memory leak behind.
1. Let's create the function `selectOnFocus()`. Add the following to the bottom of the `<script>` section of `Todo.svelte`:
```js
function selectOnFocus(node) {
if (node && typeof node.select === "function") {
// make sure node is defined and has a select() method
const onFocus = (event) => node.select(); // event handler
node.addEventListener("focus", onFocus); // when node gets focus call onFocus()
return {
destroy: () => node.removeEventListener("focus", onFocus), // this will be executed when the node is removed from the DOM
};
}
}
```
2. Now we need to tell the `<input>` to use that function with the [`use:action`](https://svelte.dev/docs/element-directives#use-action) directive:
```svelte
<input use:selectOnFocus />
```
With this directive we are telling Svelte to run this function, passing the DOM node of the `<input>` as a parameter, as soon as the component is mounted on the DOM. It will also be in charge of executing the `destroy` function when the component is removed from DOM. So with the `use` directive, Svelte takes care of the component's lifecycle for us.
In our case, our `<input>` would end up like so: update the component's first label/input pair (inside the edit template) as follows:
```svelte
<label for="todo-{todo.id}" class="todo-label">New name for '{todo.name}'</label>
<input
bind:value={name}
bind:this={nameEl}
use:selectOnFocus
type="text"
id="todo-{todo.id}"
autocomplete="off"
class="todo-text" />
```
3. Let's try it out. Go to your app, press a to-do's _Edit_ button, then <kbd>Tab</kbd> to take focus away from the `<input>`. Now click on the `<input>`, and you'll see that the entire input text is selected.
### Making the action reusable
Now let's make this function truly reusable across components. `selectOnFocus()` is just a function without any dependency on the `Todo.svelte` component, so we can just extract it to a file and use it from there.
1. Create a new file, `actions.js`, inside the `src` folder.
2. Give it the following content:
```js
export function selectOnFocus(node) {
if (node && typeof node.select === "function") {
// make sure node is defined and has a select() method
const onFocus = (event) => node.select(); // event handler
node.addEventListener("focus", onFocus); // when node gets focus call onFocus()
return {
destroy: () => node.removeEventListener("focus", onFocus), // this will be executed when the node is removed from the DOM
};
}
}
```
3. Now import it from inside `Todo.svelte`; add the following import statement just below the others:
```js
import { selectOnFocus } from "../actions.js";
```
4. And remove the `selectOnFocus()` definition from `Todo.svelte`, since we no longer need it there.
### Reusing our action
To demonstrate our action's reusability, let's make use of it in `NewTodo.svelte`.
1. Import `selectOnFocus()` from `actions.js` in this file too, as before:
```js
import { selectOnFocus } from "../actions.js";
```
2. Add the `use:selectOnFocus` directive to the `<input>`, like this:
```svelte
<input
bind:value={name}
bind:this={nameEl}
use:selectOnFocus
type="text"
id="todo-0"
autocomplete="off"
class="input input__lg" />
```
With a few lines of code we can add functionality to regular HTML elements in a very reusable and declarative way. It just takes an `import` and a short directive like `use:selectOnFocus` that clearly describes its purpose. And we can achieve this without the need to create a custom wrapper element like `TextInput`, `MyInput`, or similar. Moreover, you can add as many `use:action` directives as you want to an element.
Also, we didn't have to struggle with `onMount()`, `onDestroy()`, or `tick()` β the `use` directive takes care of the component lifecycle for us.
### Other actions improvements
In the previous section, while working with the `Todo` components, we had to deal with `bind:this`, `tick()`, and `async` functions just to give focus to our `<input>` as soon as it was added to the DOM.
1. This is how we can implement it with actions instead:
```js
const focusOnInit = (node) =>
node && typeof node.focus === "function" && node.focus();
```
2. And then in our markup we just need to add another `use:` directive:
```svelte
<input bind:value={name} use:selectOnFocus use:focusOnInit />
```
3. Our `onEdit()` function can now be much simpler:
```js
function onEdit() {
editing = true; // enter editing mode
}
```
As a last example before we move on, let's go back to our `Todo.svelte` component and give focus to the _Edit_ button after the user presses _Save_ or _Cancel_.
We could try just reusing our `focusOnInit` action again, adding `use:focusOnInit` to the _Edit_ button. But we'd be introducing a subtle bug. When you add a new to-do, the focus will be put on the _Edit_ button of the recently added to-do. That's because the `focusOnInit` action is running when the component is created.
That's not what we want β we want the _Edit_ button to receive focus only when the user has pressed _Save_ or _Cancel_.
1. So, go back to your `Todo.svelte` file.
2. First we'll create a flag named `editButtonPressed` and initialize it to `false`. Add this just below your other variable definitions:
```js
let editButtonPressed = false; // track if edit button has been pressed, to give focus to it after cancel or save
```
3. Next we'll modify the _Edit_ button's functionality to save this flag, and create the action for it. Update the `onEdit()` function like so:
```js
function onEdit() {
editButtonPressed = true; // user pressed the Edit button, focus will come back to the Edit button
editing = true; // enter editing mode
}
```
4. Below it, add the following definition for `focusEditButton()`:
```js
const focusEditButton = (node) => editButtonPressed && node.focus();
```
5. Finally we `use` the `focusEditButton` action on the _Edit_ button, like so:
```svelte
<button type="button" class="btn" on:click={onEdit} use:focusEditButton>
Edit<span class="visually-hidden"> {todo.name}</span>
</button>
```
6. Go back and try your app again. At this point, every time the _Edit_ button is added to the DOM, the `focusEditButton` action is executed, but it will only give focus to the button if the `editButtonPressed` flag is `true`.
> **Note:** We have barely scratched the surface of actions here. Actions can also have reactive parameters, and Svelte lets us detect when any of those parameters change. So we can add functionality that integrates nicely with the Svelte reactive system. For a more detailed introduction to actions, consider checking out the [Svelte Interactive tutorial](https://learn.svelte.dev/tutorial/actions) or the [Svelte `use:action` documentation](https://svelte.dev/docs/element-directives#use-action).
## Component binding: exposing component methods and variables using the `bind:this={component}` directive
There's still one accessibility annoyance left. When the user presses the _Delete_ button, the focus vanishes.
The last feature we will be looking at in this article involves setting the focus on the status heading after a to-do has been deleted.
Why the status heading? In this case, the element that had the focus has been deleted, so there's not a clear candidate to receive focus. We've picked the status heading because it's near the list of to-dos, and it's a way to give a visual feedback about the removal of the task, as well as indicating what's happened to screen reader users.
First we'll extract the status heading to its own component.
1. Create a new file, `components/TodosStatus.svelte`.
2. Add the following contents to it:
```svelte
<script>
export let todos;
$: totalTodos = todos.length;
$: completedTodos = todos.filter((todo) => todo.completed).length;
</script>
<h2 id="list-heading">
{completedTodos} out of {totalTodos} items completed
</h2>
```
3. Import the file at the beginning of `Todos.svelte`, adding the following `import` statement below the others:
```js
import TodosStatus from "./TodosStatus.svelte";
```
4. Replace the `<h2>` status heading inside `Todos.svelte` with a call to the `TodosStatus` component, passing `todos` to it as a prop, like so:
```svelte
<TodosStatus {todos} />
```
5. You can also do a bit of cleanup, removing the `totalTodos` and `completedTodos` variables from `Todos.svelte`. Just remove the `$: totalTodos = β¦` and the `$: completedTodos = β¦` lines, and also remove the reference to `totalTodos` when we calculate `newTodoId` and use `todos.length` instead. To do this, replace the block that begins with `let newTodoId` with this:
```js
$: newTodoId = todos.length ? Math.max(...todos.map((t) => t.id)) + 1 : 1;
```
6. Everything works as expected β we just extracted the last piece of markup to its own component.
Now we need to find a way to give focus to the `<h2>` status label after a to-do has been removed.
So far we saw how to send information to a component via props, and how a component can communicate with its parent by emitting events or using two-way data binding. The child component could get a reference to the `<h2>` node `using bind:this={dom_node}` and expose it to the outside using two-way data binding. But doing so would break the component encapsulation; setting focus on it should be its own responsibility.
So we need the `TodosStatus` component to expose a method that its parent can call to give focus to it. It's a very common scenario that a component needs to expose some behavior or information to the consumer; let's see how to achieve it with Svelte.
We've already seen that Svelte uses `export let varname = β¦` to [declare props](https://svelte.dev/docs/svelte-components#script-1-export-creates-a-component-prop). But if instead of using `let` you export a `const`, `class`, or `function`, it is read-only outside the component. Function expressions are valid props, however. In the following example, the first three declarations are props, and the rest are exported values:
```svelte
<script>
export let bar = "optional default initial value"; // prop
export let baz = undefined; // prop
export let format = (n) => n.toFixed(2); // prop
// these are readonly
export const thisIs = "readonly"; // read-only export
export function greet(name) {
// read-only export
alert(`Hello, ${name}!`);
}
export const greet = (name) => alert(`Hello, ${name}!`); // read-only export
</script>
```
With this in mind, let's go back to our use case. We'll create a function called `focus()` that gives focus to the `<h2>` heading. For that we'll need a `headingEl` variable to hold the reference to the DOM node, and we'll have to bind it to the `<h2>` element using `bind:this={headingEl}`. Our focus method will just run `headingEl.focus()`.
1. Update the contents of `TodosStatus.svelte` like so:
```svelte
<script>
export let todos;
$: totalTodos = todos.length;
$: completedTodos = todos.filter((todo) => todo.completed).length;
let headingEl;
export function focus() {
// shorter version: export const focus = () => headingEl.focus()
headingEl.focus();
}
</script>
<h2 id="list-heading" bind:this={headingEl} tabindex="-1">
{completedTodos} out of {totalTodos} items completed
</h2>
```
Note that we've added a `tabindex` attribute to the `<h2>` to allow the element to receive focus programmatically.
As we saw earlier, using the `bind:this={headingEl}` directive gives us a reference to the DOM node in the variable `headingEl`. Then we use `export function focus()` to expose a function that gives focus to the `<h2>` heading.
How can we access those exported values from the parent? Just as you can bind to DOM elements with the `bind:this={dom_node}` directive, you can also bind to component instances themselves with `bind:this={component}`. So, when you use `bind:this` on an HTML element, you get a reference to the DOM node, and when you do it on a Svelte component, you get a reference to the instance of that component.
2. So to bind to the instance of `TodosStatus`, we'll first create a `todosStatus` variable in `Todos.svelte`. Add the following line below your `import` statements:
```js
let todosStatus; // reference to TodosStatus instance
```
3. Next, add a `bind:this={todosStatus}` directive to the call, as follows:
```svelte
<!-- TodosStatus -->
<TodosStatus bind:this={todosStatus} {todos} />
```
4. Now we can call the `exported focus()` method from our `removeTodo()` function:
```js
function removeTodo(todo) {
todos = todos.filter((t) => t.id !== todo.id);
todosStatus.focus(); // give focus to status heading
}
```
5. Go back to your app. Now if you delete any to-do, the status heading will be focussed. This is useful to highlight the change in numbers of to-dos, both to sighted users and screen reader users.
> **Note:** You might be wondering why we need to declare a new variable for component binding. Why can't we just call `TodosStatus.focus()`? You might have multiple `TodosStatus` instances active, so you need a way to reference each particular instance. That's why you have to specify a variable to bind each specific instance to.
## The code so far
### Git
To see the state of the code as it should be at the end of this article, access your copy of our repo like this:
```bash
cd mdn-svelte-tutorial/06-stores
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/06-stores
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To see the current state of the code in a REPL, visit:
<https://svelte.dev/repl/d1fa84a5a4494366b179c87395940039?version=3.23.2>
## Summary
In this article we have finished adding all the required functionality to our app, plus we've taken care of a number of accessibility and usability issues. We also finished splitting our app into manageable components, each one with a unique responsibility.
In the meantime, we saw a few advanced Svelte techniques, like:
- Dealing with reactivity gotchas when updating objects and arrays
- Working with DOM nodes using `bind:this={dom_node}` (binding DOM elements)
- Using the component lifecycle `onMount()` function
- Forcing Svelte to resolve pending state changes with the `tick()` function
- Adding functionality to HTML elements in a reusable and declarative way with the `use:action` directive
- Accessing component methods using `bind:this={component}` (binding components)
In the next article we will see how to use stores to communicate between components, and add animations to our components.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_components","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_stores", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/ember_conditional_footer/index.md | ---
title: "Ember Interactivity: Footer functionality, conditional rendering"
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_conditional_footer
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
Now it's time to start tackling the footer functionality in our app. Here we'll get the todo counter to update to show the correct number of todos still to complete, and correctly apply styling to completed todos (i.e. where the checkbox has been checked). We'll also wire up our "Clear completed" button. Along the way, we'll learn about using conditional rendering in our templates.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
A deeper understanding of modern JavaScript features (such as classes,
modules, etc.), will be extremely beneficial, as Ember makes heavy use
of them.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To continue our learning about components classes, start looking at
conditional rendering, and wire up some of our footer functionality.
</td>
</tr>
</tbody>
</table>
## Connecting the behavior in the footer
To get the footer working, we need to implement the following three areas of functionality:
- A pending todo counter.
- Filters for all, active, and completed todos.
- A button to clear the completed todos.
1. Because we need access to our service from the footer component, we need to generate a class for the footer. Enter the following terminal command to do so:
```bash
ember generate component-class footer
```
2. Next, go and find the newly-created `todomvc/app/components/footer.js` file and update it to the following:
```js
import Component from "@glimmer/component";
import { inject as service } from "@ember/service";
export default class FooterComponent extends Component {
@service("todo-data") todos;
}
```
3. Now we need to go back to our `todo-data.js` file and add some functionality that will allow us to return the number of incomplete todos (useful for showing how many are left), and clear the completed todos out of the list (which is what the "Clear completed" functionality needs).
In `todo-data.js`, add the following getter underneath the existing `all()` getter to define what the incomplete todos actually are:
```js
get incomplete() {
return this.todos.filterBy('isCompleted', false);
}
```
Using Ember's [`ArrayProxy.filterBy()`](https://api.emberjs.com/ember/4.2/classes/ArrayProxy/methods/filterBy?anchor=filterBy) method, we're able to easily filter Objects in our array based on simple equals conditions. Here we're asking for all the todo items where the `isCompleted` property is equal to `false`, and because `isCompleted` is `@tracked` in our `Todo` object, this getter will re-compute when the value changes on an Object in the array.
4. Next, add the following action underneath the existing `add(text)` action:
```js
@action
clearCompleted() {
this.todos = this.incomplete;
}
```
This is rather nice for clearing the todos β we just need to set the `todos` array to equal the list of incomplete todos.
5. Finally, we need to make use of this new functionality in our `footer.hbs` template. Go to this file now.
6. First of all, replace this line:
```hbs
<strong>0</strong> todos left
```
With this, which populates the incomplete number with the length of the `incomplete` array:
```hbs
<strong>\{{this.todos.incomplete.length}}</strong> todos left
```
7. Next, replace this:
```hbs
<button type="button" class="clear-completed">
```
With this:
```hbs
<button type="button" class="clear-completed" \{{on 'click' this.todos.clearCompleted}}>
```
So now when the button is clicked, the `clearCompleted()` action we added earlier is run.
However, if you try to click the "Clear Completed" button now, it won't appear to do anything, because there is currently no way to "complete" a todo. We need to wire up the `todo.hbs` template to the service, so that checking the relevant checkbox changes the state of each todo. We'll do that next.
## The todo/todos plural problem
The above is fine, but we have another small issue to contend with. The "todos left" indicator always says "x todos left", even when there is only one todo left, which is bad grammar!
To fix this, we need to update this part of the template to include some conditional rendering. In Ember, you can conditionally render parts of the template using [conditional content](https://guides.emberjs.com/v3.18.0/components/conditional-content/); a simple block example looks something like this:
```hbs
\{{#if this.thingIsTrue}} Content for the block form of "if"
\{{/if}}
```
So let's try replacing this part of `footer.hbs`:
```hbs
<strong>\{{this.todos.incomplete.length}}</strong> todos left
```
with the following:
```hbs
<strong>\{{this.todos.incomplete.length}}</strong>
\{{#if this.todos.incomplete.length === 1}} todo
\{{else}} todos
\{{/if}} left
```
This will give us an error, however β in Ember, these simple if statements can currently only test for a truthy/falsy value, not a more complex expression such as a comparison. To fix this, we'll have to add a getter to `todo-data.js` to return the result of `this.incomplete.length === 1`, and then call that in our template.
Add the following new getter to `todo-data.js`, just below the existing getters. Note that here we need `this.incomplete.length`, not `this.todos.incomplete.length`, because we are doing this inside the service, where the `incomplete()` getter is available directly (in the template, the contents of the service has been made available as `todos` via the `@service('todo-data') todos;` line inside the footer class, hence it being `this.todos.incomplete.length` there).
```js
get todoCountIsOne() {
return this.incomplete.length === 1;
}
```
Then go back over to `footer.hbs` and update the previous template section we edited to the following:
```hbs
<strong>\{{this.todos.incomplete.length}}</strong>
\{{#if this.todos.todoCountIsOne}}todo\{{else}}todos\{{/if}} left
```
Now save and test, and you'll see the correct pluralization used when you only have one todo item present!
Note that this is the block form of `if` in Ember; you could also use the inline form:
```hbs
\{{if this.todos.todoCountIsOne "todo" "todos"}}
```
## Completing todos
As with the other components, we need a class to access the service.
### Creating a todo class
1. Run the following command in your terminal:
```bash
ember generate component-class todo
```
2. Now go to the newly-created `todomvc/app/components/todo.js` file and update the contents to look like so, to give the todo component access to the service:
```js
import Component from "@glimmer/component";
import { inject as service } from "@ember/service";
export default class TodoComponent extends Component {
@service("todo-data") todos;
}
```
3. Next, go back again to our `todo-data.js` service file and add the following action just below the previous ones, which will allow us to toggle a completion state for each todo:
```js
@action
toggleCompletion(todo) {
todo.isCompleted = !todo.isCompleted;
}
```
### Updating the template to show completed state
Finally, we will edit the `todo.hbs` template such that the checkbox's value is now bound to the `isCompleted` property on the todo, and so that on change, the `toggleCompletion()` method on the todo service is invoked.
1. In `todo.hbs`, first find the following line:
```hbs
<li>
```
And replace it with this β you'll notice that here we're using some more conditional content to add the class value if appropriate:
```hbs-nolint
<li class=\{{ if @todo.isCompleted 'completed' }}>
```
2. Next, find the following line:
```hbs-nolint
<input
aria-label="Toggle the completion of this todo"
class="toggle"
type="checkbox"
>
```
And replace it with this:
```hbs
<input
class="toggle"
type="checkbox"
aria-label="Toggle the completion of this todo"
checked=\{{ @todo.isCompleted }}
\{{ on 'change' (fn this.todos.toggleCompletion @todo) }}
>
```
> **Note:** The above snippet uses a new Ember-specific keyword β `fn`. `fn` allows for [partial application](https://en.wikipedia.org/wiki/Partial_application), which is similar to [`bind`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind), but it never changes the invocation context; this is equivalent to using `bind` with a `null` first argument.
Try restarting the dev server and going to `localhost:4200` again, and you'll now see that we have a fully-operational "todos left" counter and Clear button:

If you're asking yourself why we're not just doing the toggle on the component, since the function is entirely self-contained and not at all needing anything from the service, then you are 100% right to ask that question! However, because \*eventually\*, we'll want to persist or sync all changes to the todos list to [local storage](/en-US/docs/Web/API/Window/localStorage) (see the [final version of the app](https://nullvoxpopuli.github.io/ember-todomvc-tutorial/)), it makes sense to have all persistent-state-changing operations be in the same place.
## Summary
That's enough for now. At this point, not only can we mark todos as complete, but we can clear them as well. Now the only thing left to wire up the footer are the three filtering links: "All", "Active", and "Completed". We'll do that in the next article, using Routing.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_interactivity_events_state","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_routing", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/svelte_getting_started/index.md | ---
title: Getting started with Svelte
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_getting_started
page-type: learn-module-chapter
---
{{LearnSidebar}}
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_todo_list_beginning", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
In this article we'll provide a quick introduction to the [Svelte framework](https://svelte.dev/). We will see how Svelte works and what sets it apart from the rest of the frameworks and tools we've seen so far. Then we will learn how to set up our development environment, create a sample app, understand the structure of the project, and see how to run it locally and build it for production.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
<p>
At minimum, it is recommended that you are familiar with the core
<a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages, and
have knowledge of the
<a
href="/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line"
>terminal/command line</a
>.
</p>
<p>
Svelte is a compiler that generates minimal and highly optimized
JavaScript code from our sources; you'll need a terminal with node +
npm installed to compile and build your app.
</p>
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To setup a local Svelte development environment, create and build a
starter app, and understand the basics of how it works.
</td>
</tr>
</tbody>
</table>
## Svelte: A new approach to building rich user interfaces
Svelte provides a different approach to building web apps than some of the other frameworks covered in this module. While frameworks like React and Vue do the bulk of their work in the user's browser while the app is running, Svelte shifts that work into a compile step that happens only when you build your app, producing highly optimized vanilla JavaScript.
The outcome of this approach is not only smaller application bundles and better performance, but also a developer experience that is more approachable for people that have limited experience of the modern tooling ecosystem.
Svelte sticks closely to the classic web development model of HTML, CSS, and JS, just adding a few extensions to HTML and JavaScript. It arguably has fewer concepts and tools to learn than some of the other framework options.
Its main current disadvantages are that it is a young framework β its ecosystem is therefore more limited in terms of tooling, support, plugins, clear usage patterns, etc. than more mature frameworks, and there are also fewer job opportunities. But its advantages should be enough to make you interested to explore it.
> **Note:** Svelte has [official TypeScript support](https://svelte.dev/docs/typescript). We'll look at it later on in this tutorial series.
We encourage you to go through the [Svelte tutorial](https://learn.svelte.dev/) for a really quick introduction to the basic concepts, before returning to this tutorial series to learn how to build something slightly more in-depth.
## Use cases
Svelte can be used to develop small pieces of an interface or whole applications. You can either start from scratch letting Svelte drive your UI or you can incrementally integrate it into an existing application.
Nevertheless, Svelte is particularly appropriate to tackle the following situations:
- Web applications intended for low-power devices: Applications built with Svelte have smaller bundle sizes, which is ideal for devices with slow network connections and limited processing power. Less code means fewer KB to download, parse, execute, and keep hanging around in memory.
- Highly interactive pages or complex visualizations: If you are building data-visualizations that need to display a large number of DOM elements, the performance gains that come from a framework with no runtime overhead will ensure that user interactions are snappy and responsive.
- Onboarding people with basic web development knowledge: Svelte has a shallow learning curve. Web developers with basic HTML, CSS, and JavaScript knowledge can easily grasp Svelte specifics in a short time and start building web applications.
The Svelte team launched [SvelteKit](https://kit.svelte.dev), a framework for building web applications using Svelte. It contains features found in modern web frameworks, such as filesystem-based routing, server-side rendering (SSR), page-specific rendering modes, offline support, and more. For more information about SvelteKit, see the [official tutorial](https://learn.svelte.dev) and [documentation](https://kit.svelte.dev/docs).
> **Note:** SvelteKit is designed to replace [Sapper](https://sapper.svelte.dev/) as the recommended Svelte framework for building web applications.
Svelte is also available for mobile development via [Svelte Native](https://svelte-native.technology).
## How does Svelte work?
Being a compiler, Svelte can extend HTML, CSS, and JavaScript, generating optimal JavaScript code without any runtime overhead. To achieve this, Svelte extends vanilla web technologies in the following ways:
- It extends HTML by allowing JavaScript expressions in markup and providing directives to use conditions and loops, in a fashion similar to handlebars.
- It extends CSS by adding a scoping mechanism, allowing each component to define its own styles without the risk of clashing with other components' styles.
- It extends JavaScript by reinterpreting specific directives of the language to achieve true reactivity and ease component state management.
The compiler only intervenes in very specific situations and only in the context of Svelte components. Extensions to the JavaScript language are minimal and carefully picked in order not to break JavaScript syntax or alienate developers. In fact, you will be mostly working with vanilla JavaScript.
## First steps with Svelte
Since Svelte is a compiler, you can't just add a `<script src="svelte.js">` tag to your page and import it into your app. You'll have to set up your development environment in order to let the compiler do its job.
### Requirements
In order to work with Svelte, you need to have [Node.js](https://nodejs.org/) installed. It's recommended that you use the long-term support (LTS) version. Node includes npm (the node package manager), and npx (the node package runner). Note that you can also use the Yarn package manager in place of npm, but we'll assume you are using npm in this set of tutorials. See [Package management basics](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Package_management) for more information on npm and yarn.
If you're using Windows, you will need to install some software to give you parity with Unix/macOS terminal in order to use the terminal commands mentioned in this tutorial. Gitbash (which comes as part of the [git for Windows toolset](https://gitforwindows.org/)) or [Windows Subsystem for Linux (WSL)](https://docs.microsoft.com/windows/wsl/about) are both suitable. See [Command line crash course](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line) for more information on these, and on terminal commands in general.
Also see the following for more information:
- ["About npm"](https://docs.npmjs.com/about-npm) on the npm documentation
- ["Introducing npx"](https://blog.npmjs.org/post/162869356040/introducing-npx-an-npm-package-runner) on the npm blog
### Creating your first Svelte app
The easiest way to create a starter app template is to just download the starter template application. You can do that by visiting [sveltejs/template](https://github.com/sveltejs/template) on GitHub, or you can avoid having to download and unzip it and just use [degit](https://github.com/Rich-Harris/degit).
To create your starter app template, run the following terminal commands:
```bash
npx degit sveltejs/template moz-todo-svelte
cd moz-todo-svelte
npm install
npm run dev
```
> **Note:** degit doesn't do any kind of magic β it just lets you download and unzip the latest version of a git repo's contents. This is much quicker than using `git clone` because it will not download all the history of the repo, or create a complete local clone.
After running `npm run dev`, Svelte will compile and build your application. It will start a local server at `localhost:8080`. Svelte will watch for file updates, and automatically recompile and refresh the app for you when changes are made to the source files. Your browser will display something like this:

### Application structure
The starter template comes with the following structure:
```plain
moz-todo-svelte
βββ README.md
βββ package.json
βββ package-lock.json
βββ rollup.config.js
βββ .gitignore
βββ node_modules
βββ public
β βββ favicon.png
β βββ index.html
β βββ global.css
β βββ build
β βββ bundle.css
β βββ bundle.js
β βββ bundle.js.map
βββ scripts
β βββ setupTypeScript.js
βββ src
βββ App.svelte
βββ main.js
```
The contents are as follows:
- `package.json` and `package-lock.json`: Contains information about the project that Node.js/npm uses to keep it organized. You don't need to understand this file at all to complete this tutorial, however, if you'd like to learn more, you can read about [`package.json` handling](https://docs.npmjs.com/cli/configuring-npm/package-json) on npmjs.com; we also talk about it in our [Package management basics tutorial](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Package_management).
- `node_modules`: This is where node saves the project dependencies. These dependencies won't be sent to production, they are just used for development purposes.
- `.gitignore`: Tells git which files or folder to ignore from the project β useful if you decide to include your app in a git repo.
- `rollup.config.js`: Svelte uses [rollup.js](https://rollupjs.org/) as a module bundler. This configuration file tells rollup how to compile and build your app. If you prefer [webpack](https://webpack.js.org/), you can create your starter project with `npx degit sveltejs/template-webpack svelte-app` instead.
- `scripts`: Contains setup scripts as required. Currently should only contain `setupTypeScript.js`.
- `setupTypeScript.js`: This script sets up TypeScript support in Svelte. We'll talk about this more in the last article.
- `src`: This directory is where the source code for your application lives β where you'll be creating the code for your app.
- `App.svelte`: This is the top-level component of your app. So far it just renders the 'Hello World!' message.
- `main.js`: The entry point to our application. It just instantiates the `App` component and binds it to the body of our HTML page.
- `public`: This directory contains all the files that will be published in production.
- `favicon.png`: This is the favicon for your app. Currently, it's the Svelte logo.
- `index.html`: This is the main page of your app. Initially it's just an empty HTML page that loads the CSS files and js bundles generated by Svelte.
- `global.css`: This file contains unscoped styles. It's a regular CSS file that will be applied to the whole application.
- `build`: This folder contains the generated CSS and JavaScript source code.
- `bundle.css`: The CSS file that Svelte generated from the styles defined for each component.
- `bundle.js`: The JavaScript file compiled from all your JavaScript source code.
## Having a look at our first Svelte component
Components are the building blocks of Svelte applications. They are written into `.svelte` files using a superset of HTML.
All three sections β `<script>`, `<style>`, and markup β are optional, and can appear in any order you like.
```html
<script>
// logic goes here
</script>
<style>
/* styles go here */
</style>
<!-- markup (zero or more HTML elements) goes here -->
```
> **Note:** For more information on the component format, have a look at the [Svelte Components documentation](https://svelte.dev/docs/svelte-components).
With this in mind, let's have a look at the `src/App.svelte` file that came with the starter template. You should see something like the following:
```html
<script>
export let name;
</script>
<main>
<h1>Hello {name}!</h1>
<p>
Visit the <a href="https://learn.svelte.dev/">Svelte tutorial</a> to learn
how to build Svelte apps.
</p>
</main>
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
h1 {
color: #ff3e00;
text-transform: uppercase;
font-size: 4em;
font-weight: 100;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
```
### The `<script>` section
The `<script>` block contains JavaScript that runs when a component instance is created. Variables declared (or imported) at the top level are 'visible' from the component's markup. Top-level variables are the way Svelte handles the component state, and they are reactive by default. We will explain in detail what this means later on.
```html
<script>
export let name;
</script>
```
Svelte uses the [`export`](/en-US/docs/Web/JavaScript/Reference/Statements/export) keyword to mark a variable declaration as a property (or prop), which means it becomes accessible to consumers of the component (e.g. other components). This is one example of Svelte extending JavaScript syntax to make it more useful, while keeping it familiar.
### The markup section
In the markup section you can insert any HTML you like, and in addition you can insert valid JavaScript expressions inside single curly braces (`{}`). In this case we are embedding the value of the `name` prop right after the `Hello` text.
```html
<main>
<h1>Hello {name}!</h1>
<p>
Visit the <a href="https://learn.svelte.dev/">Svelte tutorial</a> to learn
how to build Svelte apps.
</p>
</main>
```
Svelte also supports tags like `{#if}`, `{#each}`, and `{#await}` β these examples allow you to conditionally render a portion of the markup, iterate through a list of elements, and work with async values, respectively.
### The `<style>` section
If you have experience working with CSS, the following snippet should make sense:
```html
<style>
main {
text-align: center;
padding: 1em;
max-width: 240px;
margin: 0 auto;
}
h1 {
color: #ff3e00;
text-transform: uppercase;
font-size: 4em;
font-weight: 100;
}
@media (min-width: 640px) {
main {
max-width: none;
}
}
</style>
```
We are applying a style to our [`<h1>`](/en-US/docs/Web/HTML/Element/Heading_Elements) element. What will happen to other components with `<h1>` elements in them?
In Svelte, CSS inside a component's `<style>` block will be scoped only to that component. This works by adding a class to selected elements, which is based on a hash of the component styles.
You can see this in action by opening `localhost:8080` in a new browser tab, right/<kbd>Ctrl</kbd>-clicking on the _HELLO WORLD!_ label, and choosing _Inspect_:

When compiling the app, Svelte changes our `h1` styles definition to `h1.svelte-1tky8bj`, and then modifies every `<h1>` element in our component to `<h1 class="svelte-1tky8bj">`, so that it picks up the styles as required.
> **Note:** You can override this behavior and apply styles to a selector globally using the `:global()` modifier (see the [Svelte `<style>` docs](https://svelte.dev/docs/svelte-components#style) for more information).
## Making a couple of changes
Now that we have a general idea of how it all fits together, we can start making a few changes.
At this point you can try updating your `App.svelte` component β for example change the `<h1>` element on line 6 of `App.svelte` so that it reads like this:
```html
<h1>Hello {name} from MDN!</h1>
```
Just save your changes and the app running at `localhost:8080` will be automatically updated.
### A first look at Svelte reactivity
In the context of a UI framework, reactivity means that the framework can automatically update the DOM when the state of any component is changed.
In Svelte, reactivity is triggered by assigning a new value to any top-level variable in a component. For example, we could include a `toggleName()` function in our `App` component, and a button to run it.
Try updating your `<script>` and markup sections like so:
```html
<script>
export let name;
function toggleName() {
if (name === "world") {
name = "Svelte";
} else {
name = "world";
}
}
</script>
<main>
<h1>Hello {name}!</h1>
<button on:click="{toggleName}">Toggle name</button>
<p>
Visit the <a href="https://learn.svelte.dev/">Svelte tutorial</a> to learn
how to build Svelte apps.
</p>
</main>
```
Whenever the button is clicked, Svelte executes the `toggleName()` function, which in turn updates the value of the `name` variable.
As you can see, the `<h1>` label is automatically updated. Behind the scenes, Svelte created the JavaScript code to update the DOM whenever the value of the name variable changes, without using any virtual DOM or other complex reconciliation mechanism.
Note the use of `:` in `on:click`. That's Svelte's syntax for listening to DOM events.
## Inspecting main.js: the entry point of our app
Let's open `src/main.js`, which is where the `App` component is being imported and used. This file is the entry point for our app, and it initially looks like this:
```js
import App from "./App.svelte";
const app = new App({
target: document.body,
props: {
name: "world",
},
});
export default app;
```
`main.js` starts by importing the Svelte component that we are going to use. Then in line 3 it instantiates it, passing an option object with the following properties:
- `target`: The DOM element inside which we want the component to be rendered, in this case the `<body>` element.
- `props`: the values to assign to each prop of the `App` component.
## A look under the hood
How does Svelte manage to make all these files work together nicely?
The Svelte compiler processes the `<style>` section of every component and compiles them into the `public/build/bundle.css` file.
It also compiles the markup and `<script>` section of every component and stores the result in `public/build/bundle.js`. It also adds the code in `src/main.js` to reference the features of each component.
Finally the file `public/index.html` includes the generated `bundle.css` and `bundle.js` files:
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Svelte app</title>
<link rel="icon" type="image/png" href="/favicon.png" />
<link rel="stylesheet" href="/global.css" />
<link rel="stylesheet" href="/build/bundle.css" />
<script defer src="/build/bundle.js"></script>
</head>
<body></body>
</html>
```
The minified version of `bundle.js` weighs a little more than 3KB, which includes the "Svelte runtime" (just 300 lines of JavaScript code) and the `App.svelte` compiled component. As you can see, `bundle.js` is the only JavaScript file referenced by `index.html`. There are no other libraries loaded into the web page.
This is a much smaller footprint than compiled bundles from other frameworks. Take into account that, in the case of code bundles, it's not just the size of the files you have to download that matter. This is executable code that needs to be parsed, executed, and kept in memory. So this really makes a difference, especially in low-powered devices or CPU-intensive applications.
## Following this tutorial
In this tutorial series you will be building a complete web application. We'll learn all the basics about Svelte and also quite a few advanced topics.
You can just read the content to get a good understanding of Svelte features, but you'll get the most out of this tutorial if you follow along coding the app with us as you go. To make it easier for you to follow each article, we provide a GitHub repository with a folder containing the source for the app as it is at the start of each tutorial.
Svelte also provides an online REPL, which is a playground for live-coding Svelte apps on the web without having to install anything on your machine. We provide a REPL for each article so you can start coding along right away. Let's talk a bit more about how to use these tools.
### Using Git
The most popular version control system is Git, along with GitHub, a site that provides hosting for your repositories and several tools for working with them.
We'll be using GitHub so that you can easily download the source code for each article. You will also be able to get the code as it should be after completing the article, just in case you get lost.
After [installing git](https://git-scm.com/downloads), to clone the repository you should execute:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then at the beginning of each article, you can just `cd` into the corresponding folder and start the app in dev mode to see what its current state should be, like this:
```bash
cd 02-starting-our-todo-app
npm install
npm run dev
```
If you want lo learn more about git and GitHub, we've compiled a list of links to useful guides β see [Git and GitHub](/en-US/docs/Learn/Tools_and_testing/GitHub).
> **Note:** If you just want to download the files without cloning the git repo, you can use the degit tool like this β `npx degit opensas/mdn-svelte-tutorial`. You can also download a specific folder with `npx degit opensas/mdn-svelte-tutorial/01-getting-started`. Degit won't create a local git repo, it will just download the files of the specified folder.
### Using the Svelte REPL
A REPL ([readβevalβprint loop](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop)) is an interactive environment that allows you to enter commands and immediately see the results β many programming languages provide a REPL.
Svelte's REPL is much more than that. It's an online tool that allows you to create complete apps, save them online, and share with others.
It's the easiest way to start playing with Svelte from any machine, without having to install anything. It is also widely used by Svelte community. If you want to share an idea, ask for help, or report an issue, it's always extremely useful to create a REPL instance demonstrating the issue.
Let's have a quick look at the Svelte REPL and how you'd use it. It looks like so:

To start a REPL, open your browser and navigate to <https://svelte.dev/repl>.
- On the left side of the screen you'll see the code of your components, and on the right you'll see the running output of your app.
- The bar above the code lets you create `.svelte` and `.js` files and rearrange them. To create a file inside a folder, just specify the complete pathname, like this: `components/MyComponent.svelte`. The folder will be automatically created.
- Above that bar you have the title of the REPL. Click on it to edit it.
- On the right side you have three tabs:
- The _Result_ tab shows your app output, and provides a console at the bottom.
- The _JS output_ tab lets you inspect the JavaScript code generated by Svelte and set compiler options.
- The _CSS output_ tab shows the CSS generated by Svelte.
- Above the tabs, you'll find a toolbar that lets you enter fullscreen mode and download your app. If you log in with a GitHub account, you'll also be able to fork and save the app. You'll also be able to see all your saved REPLs by clicking on your GitHub username profile and selecting _Your saved apps_.
Whenever you change any file on the REPL, Svelte will recompile the app and update the Result tab. To share your app, share the URL. For example, here's the link for a REPL running our complete app: <https://svelte.dev/repl/378dd79e0dfe4486a8f10823f3813190?version=3.23.2>.
> **Note:** Notice how you can specify Svelte's version in the URL. This is useful when reporting issues related to a specific version of Svelte.
We will provide a REPL at the beginning and end of each article so that you can start coding with us right away.
> **Note:** At the moment the REPL can't handle folder names properly. If you are following the tutorial on the REPL, just create all your components inside the root folder. Then when you see a path in the code, for example `import Todos from './components/Todos.svelte'`, just replace it with a flat URL, e.g. `import Todos from './Todos.svelte'`.
## The code so far
### Git
Clone the GitHub repo (if you haven't already done it) with:
```bash
git clone https://github.com/opensas/mdn-svelte-tutorial.git
```
Then to get to the current app state, run
```bash
cd mdn-svelte-tutorial/01-getting-started
```
Or directly download the folder's content:
```bash
npx degit opensas/mdn-svelte-tutorial/01-getting-started
```
Remember to run `npm install && npm run dev` to start your app in development mode.
### REPL
To code along with us using the REPL, start at
<https://svelte.dev/repl/fc68b4f059d34b9c84fa042d1cce586c?version=3.23.2>
## Summary
This brings us to the end of our initial look at Svelte, including how to install it locally, create a starter app, and how the basics work. In the next article we'll start building our first proper application, a todo list. Before we do that, however, let's recap some of the things we've learned.
In Svelte:
- We define the script, style, and markup of each component in a single `.svelte` file.
- Component props are declared with the `export` keyword.
- Svelte components can be used just by importing the corresponding `.svelte` file.
- Components styles are scoped, keeping them from clashing with each other.
- In the markup section you can include any JavaScript expression by putting it between curly braces.
- The top-level variables of a component constitute its state.
- Reactivity is fired just by assigning a new value to a top-level variable.
{{PreviousMenuNext("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_resources","Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Svelte_todo_list_beginning", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks | data/mdn-content/files/en-us/learn/tools_and_testing/client-side_javascript_frameworks/introduction/index.md | ---
title: Introduction to client-side frameworks
slug: Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Introduction
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
We begin our look at frameworks with a general overview of the area, looking at a brief history of JavaScript and frameworks, why frameworks exist and what they give us, how to start thinking about choosing a framework to learn, and what alternatives there are to client-side frameworks.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand how client-side JavaScript frameworks came to exist, what problems they solve, what alternatives there are, and how to go about choosing one.
</td>
</tr>
</tbody>
</table>
## A brief history
When JavaScript debuted in 1996, it added occasional interactivity and excitement to a web that was, up until then, composed of static documents. The web became not just a place to _read things_, but to _do things_. JavaScript's popularity steadily increased. Developers who worked with JavaScript wrote tools to solve the problems they faced, and packaged them into reusable packages called **libraries**, so they could share their solutions with others. This shared ecosystem of libraries helped shape the growth of the web.
Now, JavaScript is an essential part of the web, [used on 98% of all websites](https://w3techs.com/technologies/details/cp-javascript), and the web is an essential part of modern life. Users write papers, manage their budgets, stream music, watch movies, and communicate with others over great distances instantaneously, with text, audio, or video chat. The web allows us to do things that used to be possible only in native applications installed on our computers. These modern, complex, interactive websites are often referred to as **web applications**.
The advent of modern JavaScript frameworks has made it much easier to build highly dynamic, interactive applications. A **framework** is a library that offers opinions about how software gets built. These opinions allow for predictability and homogeneity in an application; predictability allows the software to scale to an enormous size and still be maintainable; predictability and maintainability are essential for the health and longevity of software.
JavaScript frameworks power much of the impressive software on the modern web β including many of the websites you likely use every day. MDN Web Docs, which you are currently reading this on, uses the React/ReactDOM framework to power its front end.
## What frameworks are out there?
There are many frameworks out there, but currently the "big four" are considered to be the following.
### Ember
[Ember](https://emberjs.com/) was initially released in December 2011 as a continuation of work that started in the [SproutCore](https://en.wikipedia.org/wiki/SproutCore) project. It is an older framework that has fewer users than more modern alternatives such as React and Vue, but it still enjoys a fair amount of popularity due to its stability, community support, and some clever coding principles.
[Start learning Ember](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Ember_getting_started)
### Angular
[Angular](https://angular.io) is an open-source web application framework led by the Angular Team at Google and by a community of individuals and corporations. It is a complete rewrite from the same team that built [AngularJS](https://angularjs.org/). Angular was officially released on the 14th of September 2016.
Angular is a component-based framework which uses declarative HTML templates. At build time, transparently to developers, the framework's compiler translates the templates to optimized JavaScript instructions. Angular uses [TypeScript](https://www.typescriptlang.org/), a superset of JavaScript that we'll look at in a little more detail in the next chapter.
[Start learning Angular](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Angular_getting_started)
### Vue
After working on and learning from the original [AngularJS](https://angularjs.org/) project, Evan You released [Vue](https://vuejs.org/) in 2014. Vue is the youngest of the big four, but has enjoyed a recent uptick in popularity.
Vue, like [AngularJS](https://angularjs.org/), extends HTML with some of its own code. Apart from that, it mainly relies on modern, standard JavaScript.
[Start learning Vue](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Vue_getting_started)
### React
Facebook released [React](https://react.dev/) in 2013. By this point, it had already been using React to solve many of its problems internally. Technically, React itself is _not_ a framework; it's a library for rendering UI components. React is used in combination with _other_ libraries to make applications β React and [React Native](https://reactnative.dev/) enable developers to make mobile applications; React and [ReactDOM](https://react.dev/reference/react-dom) enable them to make web applications, etc.
Because React and ReactDOM are so often used together, React is colloquially understood as a JavaScript framework. As you read through this module, we will be working with that colloquial understanding.
React extends JavaScript with HTML-like syntax, known as [JSX](https://react.dev/learn/writing-markup-with-jsx).
[Start learning React](/en-US/docs/Learn/Tools_and_testing/Client-side_JavaScript_frameworks/React_getting_started)
## Why do frameworks exist?
We've discussed the environment that inspired the creation of frameworks, but not really _why_ developers felt the need to make them. Exploring the why requires first examining the challenges of software development.
Consider a common kind of application: A to-do list creator, which we'll look at implementing using a variety of frameworks in future chapters. This application should allow users to do things like render a list of tasks, add a new task, and delete a task; and it must do this while reliably tracking and updating the data underlying the application. In software development, this underlying data is known as state.
Each of our goals is theoretically simple in isolation. We can iterate over the data to render it; we can add to an object to make a new task; we can use an identifier to find, edit, or delete a task. When we remember that the application has to let the user do _all_ of these things through the browser, some cracks start to show. **The real problem is this: every time we change our application's state, we need to update the UI to match.**
We can examine the difficulty of this problem by looking at just _one_ feature of our to-do list app: rendering a list of tasks.
## The verbosity of DOM changes
Building HTML elements and rendering them in the browser at the appropriate time takes a surprising amount of code. Let's say that our state is an array of objects structured like this:
```js
const state = [
{
id: "todo-0",
name: "Learn some frameworks!",
},
];
```
How do we show one of those tasks to our users? We want to represent each task as a list item β an HTML [`<li>`](/en-US/docs/Web/HTML/Element/li) element inside of an unordered list element (a [`<ul>`](/en-US/docs/Web/HTML/Element/ul)). How do we make it? That could look something like this:
```js
function buildTodoItemEl(id, name) {
const item = document.createElement("li");
const span = document.createElement("span");
span.textContent = name;
item.id = id;
item.appendChild(span);
item.appendChild(buildDeleteButtonEl(id));
return item;
}
```
Here, we use the [`document.createElement()`](/en-US/docs/Web/API/Document/createElement) method to make our `<li>`, and several more lines of code to create the properties and child elements it needs.
The previous snippet references another build function: `buildDeleteButtonEl()`. It follows a similar pattern to the one we used to build a list item element:
```js
function buildDeleteButtonEl(id) {
const button = document.createElement("button");
button.setAttribute("type", "button");
button.textContent "Delete";
return button;
}
```
This button doesn't do anything yet, but it will later once we decide to implement our delete feature. The code that will render our items on the page might read something like this:
```js
function renderTodoList() {
const frag = document.createDocumentFragment();
state.tasks.forEach((task) => {
const item = buildTodoItemEl(task.id, task.name);
frag.appendChild(item);
});
while (todoListEl.firstChild) {
todoListEl.removeChild(todoListEl.firstChild);
}
todoListEl.appendChild(frag);
}
```
We've now got almost thirty lines of code dedicated _just_ to the UI β _just_ to render something in the DOM β and at no point do we add classes that we could use later to style our list-items!
Working directly with the DOM, as in this example, requires understanding many things about how the DOM works: how to make elements; how to change their properties; how to put elements inside of each other; how to get them on the page. None of this code actually handles user interactions, or addresses adding or deleting a task. If we add those features, we have to remember to update our UI at the right time and in the right way.
JavaScript frameworks were created to make this kind of work a lot easier β they exist to provide a better _developer experience_. They don't bring brand-new powers to JavaScript; they give you easier access to JavaScript's powers so you can build for today's web.
If you want to see code samples from this section in action, you can check out a [working version of the app on CodePen](https://codepen.io/mxmason/pen/XWbPNmw), which also allows users to add and delete new tasks.
Read more about the JavaScript features used in this section:
- [`Array.forEach()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)
- [`Document.createDocumentFragment()`](/en-US/docs/Web/API/Document/createDocumentFragment)
- [`Document.createElement()`](/en-US/docs/Web/API/Document/createElement)
- [`Element.setAttribute()`](/en-US/docs/Web/API/Element/setAttribute)
- [`Node.appendChild()`](/en-US/docs/Web/API/Node/appendChild)
- [`Node.removeChild()`](/en-US/docs/Web/API/Node/removeChild)
- [`Node.textContent`](/en-US/docs/Web/API/Node/textContent)
## Another way to build UIs
Every JavaScript framework offers a way to write user interfaces more _declaratively_. That is, they allow you to write code that describes how your UI should look, and the framework makes it happen in the DOM behind the scenes.
The vanilla JavaScript approach to building out new DOM elements in repetition was difficult to understand at a glance. By contrast, the following block of code illustrates the way you might use Vue to describe our list of tasks:
```html
<ul>
<li v-for="task in tasks" v-bind:key="task.id">
<span>\{{task.name\}}</span>
<button type="button">Delete</button>
</li>
</ul>
```
That's it. This snippet reduces almost thirty lines of code down to six lines. If the curly braces and `v-` attributes here are unfamiliar to you, that's okay; you'll learn about Vue-specific syntax later on in the module. The thing to take away here is that this code looks like the UI it represents, whereas the vanilla JavaScript code does not.
Thanks to Vue, we didn't have to write our own functions for building the UI; the framework will handle that for us in an optimized, efficient way. Our only role here was to describe to Vue what each item should look like. Developers who are familiar with Vue can quickly work out what is going on when they join our project. Vue is not alone in this: using a framework improves team as well as individual efficiency.
It's possible to do things _similar_ to this in vanilla JavaScript. [Template literal strings](/en-US/docs/Web/JavaScript/Reference/Template_literals) make it easy to write strings of HTML that represent what the final element would look like. That might be a useful idea for something as simple as our to-do list application, but it's not maintainable for large applications that manage thousands of records of data, and could render just as many unique elements in a user interface.
## Other things frameworks give us
Let's look at some of the other advantages offered by frameworks. As we've alluded to before, the advantages of frameworks are achievable in vanilla JavaScript, but using a framework takes away all of the cognitive load of having to solve these problems yourself.
### Tooling
Because each of the frameworks in this module have a large, active community, each framework's ecosystem provides tooling that improves the developer experience. These tools make it easy to add things like testing (to ensure that your application behaves as it should) or linting (to ensure that your code is error-free and stylistically consistent).
> **Note:** If you want to find out more details about web tooling concepts, check out our [Client-side tooling overview](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Overview).
### Compartmentalization
Most major frameworks encourage developers to abstract the different parts of their user interfaces into _components_ β maintainable, reusable chunks of code that can communicate with one another. All the code related to a given component can live in one file (or a couple of specific files) so that you as a developer know exactly where to go to make changes to that component. In a vanilla JavaScript app, you'd have to create your own set of conventions to achieve this in an efficient, scalable way. Many JavaScript developers, if left to their own devices, could end up with all the code related to one part of the UI being spread out all over a file β or in another file altogether.
### Routing
The most essential feature of the web is that it allows users to navigate from one page to another β it is, after all, a network of interlinked documents. When you follow a link on this very website, your browser communicates with a server and fetches new content to display for you. As it does so, the URL in your address bar changes. You can save this new URL and come back to the page later on, or share it with others so they can easily find the same page. Your browser remembers your navigation history and allows you to navigate back and forth, too. This is called **server-side routing**.
Modern web applications typically do not fetch and render new HTML files β they load a single HTML shell, and continually update the DOM inside it (referred to as **single page apps**, or **SPAs**) without navigating users to new addresses on the web. Each new pseudo-webpage is usually called a _view_, and by default, no routing is done.
When an SPA is complex enough, and renders enough unique views, it's important to bring routing functionality into your application. People are used to being able to link to specific pages in an application, travel forward and backward in their navigation history, etc., and their experience suffers when these standard web features are broken. When routing is handled by a client application in this fashion, it is aptly called **client-side routing**.
It's _possible_ to make a router using the native capabilities of JavaScript and the browser, but popular, actively developed frameworks have companion libraries that make routing a more intuitive part of the development process.
## Things to consider when using frameworks
Being an effective web developer means using the most appropriate tools for the job. JavaScript frameworks make front-end application development easy, but they are not a silver bullet that will solve all problems. This section talks about some of the things you should consider when using frameworks. Bear in mind that you might not need a framework at all β beware that you don't end up using a framework just for the sake of it.
### Familiarity with the tool
Just like vanilla JavaScript, frameworks take time to learn and have their quirks. Before you decide to use a framework for a project, be sure you have time to learn enough of its features for it to be useful to you rather than it working against you, and be sure that your teammates are comfortable with it as well.
### Overengineering
If your web development project is a personal portfolio with a few pages, and those pages have little or no interactive capability, a framework (and all of its JavaScript) may not be necessary at all. That said, frameworks are not monolithic, and some of them are better suited to small projects than others. In an article for Smashing Magazine, Sarah Drasner writes about how [Vue can replace jQuery](https://www.smashingmagazine.com/2018/02/jquery-vue-javascript/) as a tool for making small portions of a webpage interactive.
### Larger code base and abstraction
Frameworks allow you to write more declarative code β and sometimes _less_ code overall β by dealing with the DOM interactions for you, behind the scenes. This abstraction is great for your experience as a developer, but it isn't free. In order to translate what you write into DOM changes, frameworks have to run their own code, which in turn makes your final piece of software larger and more computationally expensive to operate.
Some extra code is inevitable, and a framework that supports tree-shaking (removal of any code that isn't actually used in the app during the build process) will allow you to keep your applications small, but this is still a factor you need to keep in mind when considering your app's performance, especially on more network/storage-constrained devices, like mobile phones.
The abstraction of frameworks affects not only your JavaScript, but also your relationship with the very nature of the web. No matter how you build for the web, the end result, the layer that your users ultimately interact with, is HTML. Writing your whole application in JavaScript can make you lose sight of HTML and the purpose of its various tags, and lead you to produce an HTML document that is un-semantic and inaccessible. In fact, it's possible to write a fragile application that depends entirely on JavaScript and will not function without it.
Frameworks are not the source of our problems. With the wrong priorities, any application can be fragile, bloated, and inaccessible. Frameworks do, however, amplify our priorities as developers. If your priority is to make a complex web app, it's easy to do that. However, if your priorities don't carefully guard performance and accessibility, frameworks will amplify your fragility, your bloat, and your inaccessibility. Modern developer priorities, amplified by frameworks, have inverted the structure of the web in many places. Instead of a robust, content-first network of documents, the web now often puts JavaScript first and user experience last.
## Accessibility on a framework-driven web
Let's build on what we said in the previous section, and talk a bit more about accessibility. Making user interfaces accessible always requires some thought and effort, and frameworks can complicate that process. You often have to employ advanced framework APIs to access native browser features like ARIA [live regions](/en-US/docs/Web/Accessibility/ARIA/ARIA_Live_Regions) or focus management.
In some cases, framework applications create accessibility barriers that do not exist for traditional websites. The biggest example of this is in client-side routing, as mentioned earlier.
With traditional (server-side) routing, navigating the web has predictable results. The browser knows to set focus to the top of the page and assistive technologies will announce the title of the page. These things happen every time you navigate to a new page.
With client-side routing, your browser is not loading new web pages, so it doesn't know that it should automatically adjust focus or announce a new page title. Framework authors have devoted immense time and labor to writing JavaScript that recreates these features, and even then, no framework has done so perfectly.
The upshot is that you should consider accessibility from the very start of _every_ web project, but bear in mind that abstracted codebases that use frameworks are more likely to suffer from major accessibility issues if you don't.
## How to choose a framework
Each of the frameworks discussed in this module takes different approaches to web application development. Each is regularly improving or changing, and each has its pros and cons. Choosing the right framework is a team- and project-dependent process, and you should do your own research to uncover what suits your needs. That said, we've identified a few questions you can ask in order to research your options more effectively:
1. What browsers does the framework support?
2. What domain-specific languages does the framework utilize?
3. Does the framework have a strong community and good docs (and other support) available?
The table in this section provides a glanceable summary of the current _browser support_ offered by each framework, as well as the **domain-specific languages** with which it can be used.
Broadly, {{Glossary("DSL/Domain_specific_language", "domain-specific languages (DSLs)")}} are programming languages relevant in specific areas of software development. In the context of frameworks, DSLs are variations on JavaScript or HTML that make it easier to develop with that framework. Crucially, none of the frameworks _require_ a developer to use a specific DSL, but they have almost all been designed with a specific DSL in mind. Choosing not to employ a framework's preferred DSL will mean you miss out on features that would otherwise improve your developer experience.
You should seriously consider the support matrix and DSLs of a framework when making a choice for any new project. Mismatched browser support can be a barrier to your users; mismatched DSL support can be a barrier to you and your teammates.
| Framework | Browser support | Preferred DSL | Supported DSLs | Citation |
| --------- | ----------------------------------- | ------------- | ---------------------- | ------------------------------------------------------------------------------- |
| Angular | Modern | TypeScript | HTML-based; TypeScript | [official docs](https://angular.io/guide/browser-support) |
| React | Modern | JSX | JSX; TypeScript | [official docs](https://react.dev/reference/react-dom/client#browser-support) |
| Vue | Modern (IE9+ in Vue 2) | HTML-based | HTML-based, JSX, Pug | [official docs](https://cli.vuejs.org/guide/browser-compatibility.html) |
| Ember | Modern (IE9+ in Ember version 2.18) | Handlebars | Handlebars, TypeScript | [official docs](https://guides.emberjs.com/v3.3.0/templates/handlebars-basics/) |
> **Note:** DSLs we've described as "HTML-based" do not have official names. They are not really true DSLs, but they are non-standard HTML, so we believe they are worth highlighting.
### Does the framework have a strong community?
This is perhaps the hardest metric to measure because community size does not correlate directly to easy-to-access numbers. You can check a project's number of GitHub stars or weekly npm downloads to get an idea of its popularity, but sometimes the best thing to do is search a few forums or talk to other developers. It is not just about the community's size, but also how welcoming and inclusive it is, and how good the available documentation is.
### Opinions on the web
Don't just take our word on this matter β there are discussions all over the web. The Wikimedia Foundation recently chose to use Vue for its front-end, and posted a [request for comments (RFC) on framework adoption](https://phabricator.wikimedia.org/T241180). Eric Gardner, the author of the RFC, took time to outline the needs of the Wikimedia project and why certain frameworks were good choices for the team. This RFC serves as a great example of the kind of research you should do for yourself when planning to use a front-end framework.
The [State of JavaScript survey](https://stateofjs.com/) is a helpful collection of feedback from JavaScript developers. It covers many topics related to JavaScript, including data about both the use of frameworks and developer sentiment toward them. Currently, there are several years of data available, allowing you to get a sense of a framework's popularity.
The Vue team has [exhaustively compared Vue to other popular frameworks](https://v2.vuejs.org/v2/guide/comparison.html). There may be some bias in this comparison (which they note), but it's a valuable resource nonetheless.
## Alternatives to client-side frameworks
If you're looking for tools to expedite the web development process, and you know your project isn't going to require intensive client-side JavaScript, you could reach for one of a handful of other solutions for building the web:
- A content management system
- Server-side rendering
- A static site generator
### Content management systems
**Content-management systems** (**CMSes**) are any tools that allow a user to create content for the web without directly writing code themselves. They're a good solution for large projects, especially projects that require input from content writers who have limited coding ability, or for programmers who want to save time. They do, however, require a significant amount of time to set up, and utilizing a CMS means that you surrender at least some measure of control over the final output of your website. For example: if your chosen CMS doesn't author accessible content by default, it's often difficult to improve this.
A few popular CMS systems include [Wordpress](https://wordpress.com/), [Joomla](https://www.joomla.org/), and [Drupal](https://www.drupal.org/).
### Server-side rendering
**Server-side rendering** (**SSR**) is an application architecture in which it is the _server_'s job to render a single-page application. This is the opposite of _client-side rendering_, which is the most common and most straightforward way to build a JavaScript application. Server-side rendering is easier on the client's device because you're only sending a rendered HTML file to them, but it can be difficult to set up compared to a client-side-rendered application.
All of the frameworks covered in this module support server-side rendering as well as client-side rendering. Check out [Next.js](https://nextjs.org/) for React, [Nuxt](https://nuxt.com/) for Vue (yes, it is confusing, and no, these projects are not related!), [FastBoot](https://github.com/ember-fastboot/ember-cli-fastboot) for Ember, and [Angular Universal](https://angular.io/guide/universal) for Angular.
> **Note:** Some SSR solutions are written and maintained by the community, whereas some are "official" solutions provided by the framework's maintainer.
### Static site generators
Static site generators are programs that dynamically generate all the webpages of a multi-page website β including any relevant CSS or JavaScript β so that they can be published in any number of places. The publishing host could be a GitHub pages branch, a Netlify instance, or any private server of your choosing, for example. There are a number of advantages of this approach, mostly around performance (your user's device isn't building the page with JavaScript; it's already complete) and security (static pages have fewer attack vectors). These sites can still utilize JavaScript where they need to, but they are not _dependent_ upon it. Static site generators take time to learn, just like any other tool, which can be a barrier to your development process.
Static sites can have as few or as many unique pages as you want. Just as frameworks empower you to quickly write client-side JavaScript applications, static site generators allow you a way to quickly create HTML files you would otherwise have written individually. Like frameworks, static site generators allow developers to write components that define common pieces of your web pages, and to compose those components together to create a final page. In the context of static site generators, these components are called **templates**. Web pages built by static site generators can even be home to framework applications: if you want one specific page of your statically-generated website to boot up a React application when your user visits it for example, you can do that.
Static site generators have been around for quite a long time, and they've recently seen a wave of renewed interest and innovation. A handful of powerful options are now available, such as [Astro](https://astro.build/), [Eleventy](https://www.11ty.dev/), [Hugo](https://gohugo.io/), [Jekyll](https://jekyllrb.com/), and [Gatsby](https://www.gatsbyjs.com/).
If you'd like to learn more about static site generators on the whole, check out Tatiana Mac's [Beginner's guide to Eleventy](https://www.tatianamac.com/posts/beginner-eleventy-tutorial-parti/). In the first article of the series, they explain what a static site generator is, and how it relates to other means of publishing web content.
## Summary
And that brings us to the end of our introduction to frameworks β we've not taught you any code yet, but hopefully we've given you a useful background on why you'd use frameworks in the first place and how to go about choosing one, and made you excited to learn more and get stuck in!
Our next article goes down to a lower level, looking at the specific kinds of features frameworks tend to offer, and why they work as they do.
{{NextMenu("Learn/Tools_and_testing/Client-side_JavaScript_frameworks/Main_features", "Learn/Tools_and_testing/Client-side_JavaScript_frameworks")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing | data/mdn-content/files/en-us/learn/tools_and_testing/understanding_client-side_tools/index.md | ---
title: Understanding client-side web development tools
slug: Learn/Tools_and_testing/Understanding_client-side_tools
page-type: learn-module
---
{{LearnSidebar}}
Client-side tooling can be intimidating, but this series of articles aims to illustrate the purpose of some of the most common client-side tool types, explain the tools you can chain together, how to install them using package managers, and control them using the command line. We finish up by providing a complete toolchain example showing you how to get productive.
## Prerequisites
You should really learn the basics of the core [HTML](/en-US/docs/Learn/HTML), [CSS](/en-US/docs/Learn/CSS), and [JavaScript](/en-US/docs/Learn/JavaScript) languages first before attempting to use the tools detailed here.
> **Callout:**
>
> #### Looking to become a front-end web developer?
>
> We have put together a course that includes all the essential information you need to
> work towards your goal.
>
> [**Get started**](/en-US/docs/Learn/Front-end_web_developer)
## Guides
- [1. Client-side tooling overview](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Overview)
- : In this article we provide an overview of modern web tooling, what kinds of tools are available and where you'll meet them in the lifecycle of web app development, and how to find help with individual tools.
- [2. Command line crash course](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line)
- : In your development process you'll undoubtedly be required to run some command in the terminal (or on the "command line" β these are effectively the same thing). This article provides an introduction to the terminal, the essential commands you'll need to enter into it, how to chain commands together, and how to add your own command line interface (CLI) tools.
- [3. Package management basics](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Package_management)
- : In this article we'll look at package managers in some detail to understand how we can use them in our own projects β to install project tool dependencies, keep them up-to-date, and more.
- [4. Introducing a complete toolchain](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Introducing_complete_toolchain)
- : In the final couple of articles in the series we will solidify your tooling knowledge by walking you through the process of building up a sample case study toolchain. We'll go all the way from setting up a sensible development environment and putting transformation tools in place to actually deploying your app on Netlify. In this article we'll introduce the case study, set up our development environment, and set up our code transformation tools.
- [5. Deploying our app](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Deployment)
- : In the final article in our series, we take the example toolchain we built up in the previous article and add to it so that we can deploy our sample app. We push the code to GitHub, deploy it using Netlify, and even show you how to add a simple test into the process.
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/understanding_client-side_tools | data/mdn-content/files/en-us/learn/tools_and_testing/understanding_client-side_tools/deployment/index.md | ---
title: Deploying our app
slug: Learn/Tools_and_testing/Understanding_client-side_tools/Deployment
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenu("Learn/Tools_and_testing/Understanding_client-side_tools/Introducing_complete_toolchain", "Learn/Tools_and_testing/Understanding_client-side_tools")}}
In the final article in our series, we take the example toolchain we built up in the previous article and add to it so that we can deploy our sample app. We push the code to GitHub, deploy it using Netlify, and even show you how to add a simple test into the process.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To finish working through our complete toolchain case study, focusing on
deploying the app.
</td>
</tr>
</tbody>
</table>
## Post development
There's potentially a large range of problems to be solved in this section of the project's lifecycle. As such, it's important to create a toolchain that handles these problems in a way that requires as little manual intervention as possible.
Here's just a few things to consider for this particular project:
- Generating a production build: Ensuring files are minimized, chunked, have tree-shaking applied, and that versions are "cache busted".
- Running tests: These can range from "is this code formatted properly?" to "does this thing do what I expect?", and ensuring failing tests prevent deployment.
- Actually deploying the updated code to a live URL: Or potentially a staging URL so it can be reviewed first.
> **Note:** Cache busting is a new term that we haven't met before in the module. This is the strategy of breaking a browser's own caching mechanism, which forces the browser to download a new copy of your code. Parcel (and indeed many other tools) will generate filenames that are unique to each new build. This unique filename "busts" your browser's cache, thereby making sure the browser downloads the fresh code each time an update is made to the deployed code.
The above tasks also break down into further tasks; note that most web development teams will have their own terms and processes for at least some part of the post-development phase.
For this project, we're going to use [Netlify](https://www.netlify.com/)'s wonderful static hosting offering to host our project. Netlify gives us hosting or more specifically, a URL to view your project online and to share it with your friends, family, and colleagues.
Deploying to hosting tends to be at the tail-end of the project life cycle, but with services such as Netlify bringing down the cost of deployments (both in financial terms and also the time required to actually deploy) it's possible to deploy during development to either share work in progress or to have a pre-release for some other purpose.
Netlify, amongst other things, also allows you to run pre-deployment tasks, which in our case means that all the production code build processes can be performed inside of Netlify and if the build is successful, the website changes will be deployed.
Although Netlify offers a [drag and drop deployment service](https://app.netlify.com/drop), we are intending to trigger a new deployment to Netlify each time we push to a GitHub repo.
It's exactly these kinds of connected services that we would encourage you to look for when deciding on your own build toolchain. We can commit our code and push to GitHub and the updated code will automatically trigger the entire build routine. If all is well, we get a live change deployed automatically. The _only_ action we need to perform is that initial "push".
However, we do have to set these steps up, and we'll look at that now.
## The build process
Again, because we're using Parcel for development, the build option is extremely simple to add. Instead of running the server with `npx parcel src/index.html`, we can run it with `npx parcel build src/index.html` and Parcel will build everything ready for production instead of just running it for development and testing purposes. This includes doing minification and tree-shaking of code, and cache-busting on filenames.
The newly-created production code is placed in a new directory called `dist`, which contains _all_ the files required to run the website, ready for you to upload to a server.
However, doing this step manually isn't our final aim β what we want is for the build to happen automatically and the result of the `dist` directory to be deployed live on our website.
This is where our code, GitHub, and Netlify need to be set up to talk to one another, so that each time we update our GitHub code repository, Netlify will automatically pick up the changes, run the build tasks, and finally release a new update.
We're going to add the build command to our `package.json` file as an npm script, so that the command `npm run build` will trigger the build process. This step isn't necessary, but it is a good best practice to get into the habit of setting up β across all our projects, we can then rely on `npm run build` to always do the complete build step, without needing to remember the specific build command arguments for each project.
1. Open the `package.json` file in your project's root directory, and find the `scripts` property.
2. We'll add a `build` command that we can run to build our code. Add the following line to your project now:
```json
"scripts": {
// β¦
"build": "parcel build src/index.html"
}
```
> **Note:** If the `scripts` property already has a command inside it, put a comma at the end of it. Keep the JSON valid.
3. You should now be able to run the following command in the root of your project directory to run the production build step (first quit the running process with <kbd>Ctrl</kbd> + <kbd>C</kbd> if you need to):
```bash
npm run build
```
This should give you an output like the following, showing you the production files that were created, how big they are, and how long they took to build:
```bash
dist/src.99d8a31a.js.map 446.15 KB 63ms
dist/src.99d8a31a.js 172.51 KB 5.55s
dist/stars.7f1dd035.svg 6.31 KB 145ms
dist/asteroid2.3ead4904.svg 3.51 KB 155ms
dist/asteroid1.698d75e9.svg 2.9 KB 153ms
dist/src.84f2edd1.css.map 2.57 KB 3ms
dist/src.84f2edd1.css 1.25 KB 1.53s
dist/bg.084d3fd3.svg 795 B 147ms
dist/index.html 354 B 944ms
```
Try it now!
For you to create your own instance of this project you will need to host this project's code in your own git repository. Our next step is to push the project to GitHub.
## Committing changes to GitHub
This section will get you over the line to storing your code in a git repository, but it is a far cry from a git tutorial. There are many great tutorials and books available, and our [Git and GitHub](/en-US/docs/Learn/Tools_and_testing/GitHub) page is a good place to start.
We initialized our working directory as a git working directory earlier on. A quick way to verify this is to run the following command:
```bash
git status
```
You should get a status report of what files are being tracked, what files are staged, and so on β all terms that are part of the git grammar. If you get the error `fatal: not a git repository` returned, then the working directory is not a git working directory and you'll need to initialise git using `git init`.
Now we have three tasks ahead of us:
- Add any changes we've made to the stage (a special name for the place that git will commit files from).
- Commit the changes to the repository.
- Push the changes to GitHub.
1. To add changes, run the following command:
```bash
git add .
```
Note the period at the end, it means "everything in this directory". The `git add .` command is a bit of a sledgehammer approach β it will add all local changes you've worked on in one go. If you want finer control over what you add, then use `git add -p` for an interactive process, or add individual files using `git add path/to/file`.
2. Now all the code is staged, we can commit; run the following command:
```bash
git commit -m 'committing initial code'
```
> **Note:** Although you're free to write whatever you wish in the commit message, there's some useful tips around the web on good commit messages. Keep them short, concise, and descriptive, so they clearly describe what the change does.
3. Finally, the code needs to be pushed to your GitHub-hosted repository. Let's do that now.
Over at GitHub, visit <https://github.com/new> and create your own repository to host this code.
4. Give your repository a short, memorable name, without spaces in it (use hyphens to separate words), and a description, then click _Create repository_ at the bottom of the page.
You should now have a "remote" URL that points to your new GitHub repo.

5. This remote location needs to be added to our local git repository before we can push it up there, otherwise it won't be able to find it. You'll need to run a command with the following structure (use the provided HTTPS option for now β especially if you are new to GitHub β not the SSH option):
```bash
git remote add github https://github.com/yourname/repo-name.git
```
So if your remote URL was `https://github.com/remy/super-website.git`, as in the screenshot above, your command would be
```bash
git remote add github https://github.com/remy/super-website.git
```
Change the URL to your own repository, and run it now.
6. Now we're ready to push our code to GitHub; run the following command now:
```bash
git push github main
```
At this point, you'll be prompted to enter a username and password before Git will allow the push to be sent. This is because we used the HTTPS option rather than the SSH option, as seen in the screenshot earlier. For this, you need your GitHub username and then β if you do not have two-factor authentication (2FA) turned on β your GitHub password. We would always encourage you to use 2FA if possible, but bear in mind that if you do, you'll also need to use a "personal access token". GitHub help pages has an [excellent and simple walkthrough covering how to get one](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token).
> **Note:** If you are interested in using the SSH option, thereby avoiding the need to enter your username and password every time you push to GitHub, [this tutorial walks you through how](https://docs.github.com/en/authentication/connecting-to-github-with-ssh).
This final command instructs git to push the code (aka publish) to the "remote" location that we called `github` (that's the repository hosted on github.com β we could have called it anything we like) using the branch `main`. We've not encountered branches at all, but the "main" branch is the default place for our work and it's what git starts on. It's also the default branch that Netlify will look for, which is convenient.
> **Note:** Until October 2020 the default branch on GitHub was `master`, which for various social reasons was switched to `main`. You should be aware that this older default branch may appear in various projects you encounter, but we'd suggest using `main` for your own projects.
So with our project committed in git and pushed to our GitHub repository, the next step in the toolchain is to connect GitHub to Netlify so our project can be deployed live on the web!
## Using Netlify for deployment
Deploying from GitHub to Netlify is surprisingly simple once you know the steps, particularly with "static websites" such as this project.
> **Note:** There are also a lot of [guides and tutorials on Netlify](https://www.netlify.com/blog/tutorials/) to help you improve your development workflow.
Let's get this done:
1. Go to <https://app.netlify.com/start>.
2. Press the GitHub button underneath the _Continuous Deployment_ heading. "Continuous Deployment" means that whenever the code repository changes, Netlify will (try) to deploy the code, thus it being "continuous".

3. Depending on whether you authorized Netlify before, you might need to authorize Netlify with GitHub, and choose what account you want to authorize it for (if you have multiple GitHub accounts or orgs). Choose the one you pushed your project to.
4. Netlify will prompt you with a list of the GitHub repositories it can find. Select your project repository and proceed to the next step.
5. Since we've connected Netlify to our GitHub account and given it access to deploy the project repository, Netlify will ask _how_ to prepare the project for deployment and _what_ to deploy.
You should enter the command `npm run build` for the _Build command_, and specify the `dist` directory for the _Publish directory_ β this contains the code that we want to make public.
6. To finish up, click _Deploy site_.

7. After a short wait for the deployment to occur, you should get a URL that you can go to, to see your published site β try it out!
8. And even better, whenever we make a change and _push_ the change to our remote git repository (on GitHub), this will trigger a notification to Netlify which will then run our specified build task and then deploy the resulting `dist` directory to our published site.
Try it now β make a small change to your app, and then push it to GitHub using these commands:
```bash
git add .
git commit -m 'simple netlify test'
git push github main
```
You should see your published site update with the change β this might take a few minutes to publish, so have a little patience.
That's it for Netlify. We can optionally change the name of the Netlify project or specify to use our own domain name, which Netlify offers some [excellent documentation](https://docs.netlify.com/) on.
Now for one final link in our toolchain: a test to ensure our code works.
## Testing
Testing itself is a vast subject, even within the realm of front-end development. I'll show you how to add an initial test to your project and how to use the test to prevent or to allow the project deployment to happen.
When approaching tests there are a good deal of ways to approach the problem:
- End-to-end testing, which involves your visitor clicking a thing and some other thing happening.
- Integration testing, which basically says "does one block of code still work when connected to another block?"
- Unit testing, where small and specific bits of functionality are tested to see if they do what they are supposed to do.
- [And many more types](https://en.wikipedia.org/wiki/Functional_testing). Also, see our [cross browser testing module](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing) for a bunch of useful testing information
Remember also that tests are not limited to JavaScript; tests can be run against the rendered DOM, user interactions, CSS, and even how a page looks.
However, for this project we're going to create a small test that will check the third-party NASA data feed and ensure it's in the correct format. If not, the test will fail and will prevent the project from going live. To do anything else would be beyond the scope of this module β testing is a huge subject that really requires its own separate module. We are hoping that this section will at least make you aware of the need for testing, and will plant the seed that inspires you to go and learn more.
Although the test for this project does not include a test framework, as with all things in the front-end development world, there are a slew of [framework options](https://www.npmjs.com/search?q=keywords%3Atesting).
The test itself isn't what is important. What is important is how the failure or success is handled. Some deployment platforms will include a specific method for testing as part of their pipeline. Products like GitHub, GitLab, etc., all support running tests against individual commits.
As this project is deploying to Netlify, and Netlify only asks about the build command, we will have to make the tests part of the build. If the test fails, the build fails, and Netlify won't deploy.
Let's get started.
1. Go to your `package.json` file and open it up.
2. Find your `scripts` member, and update it so that it contains the following test and build commands:
```json
"scripts": {
β¦
"test": "node tests/*.js",
"build": "npm run test && parcel build src/index.html"
}
```
3. Now of course we need to add the test to our codebase; create a new directory in your root directory called tests:
```bash
mkdir tests
```
4. Inside the new directory, create a test file:
```bash
cd tests
touch nasa-feed.test.js
```
5. Open this file, and add the contents of [nasa-feed.test.js](https://raw.githubusercontent.com/remy/mdn-will-it-miss/master/tests/nasa-feed.test.js) to it:
6. This test uses the axios package to fetch the data feed we want to test; to install this dependency, run the following command:
```bash
npm install --save-dev axios
```
We need to manually install axios because Parcel won't help us with this dependency. Our tests are outside of Parcel's view of our system β since Parcel never sees nor runs any of the test code, we're left to install the dependency ourselves.
7. Now to manually run the test, from the command line we can run:
```bash
npm run test
```
The result, if successful, is β¦ nothing. This is considered a success. In general, we only want tests to be noisy if there's something wrong. The test also exited with a special signal that tells the command line that it was successful β an exit signal of 0. If there's a failure the test fails with an exit code of 1 β this is a system-level value that says "something failed".
The `npm run test` command will use node to run all the files that are in the tests directory that end with `.js`.
In our build script, `npm run test` is called, then you see the string `&&` β this means "if the thing on the left succeeded (exited with zero), then do this thing on the right". So this translates into: if the tests pass, then build the code.
8. You'll have to upload your new code to GitHub, using similar commands to what you used before:
```bash
git add .
git commit -m 'adding test'
git push github main
```
In some cases you might want to test the result of the built code (since this isn't quite the original code we wrote), so the test might need to be run after the build command. You'll need to consider all these individual aspects whilst you're working on your own projects.
Now, finally, a minute or so after pushing, Netlify will deploy the project update. But only if it passes the test that was introduced.
## Summary
That's it for our sample case study, and for the module! We hope you found it useful. While there is a long way to go before you can consider yourself a client-side tooling wizard, we are hoping that this module has given you that first important step towards understanding client-side tooling, and the confidence to learn more and try out new things.
Let's summarize all the parts of the toolchain:
- Code quality and maintenance are performed by ESLint and Prettier. These tools are added as `devDependencies` to the project via `npm install --dev eslint prettier eslint-plugin-react` (the ESLint plugin is needed because this particular project uses React).
- There are two configuration files that the code quality tools read: `.eslintrc` and `.prettierrc`.
- During development, we use Parcel to handle our dependencies. `parcel src/index.html` is running in the background to watch for changes and to automatically build our source.
- Deployment is handled by pushing our changes to GitHub (on the "main" branch), which triggers a build and deployment on Netlify to publish the project. For our instance this URL is [near-misses.netlify.com](https://near-misses.netlify.app/); you will have your own unique URL.
- We also have a simple test that blocks the building and deployment of the site if the NASA API feed isn't giving us the correct data format.
For those of you wanting a challenge, consider whether you can optimize some part of this toolchain. Some questions to ask yourself:
- Can [images be compressed](https://github.com/ralscha/parcel-plugin-compress) during the build step?
- Could React be swapped out for [something smaller](https://preactjs.com/)?
- Could you add more tests to prevent a bad build from deploying, such as [performance audits](https://developer.chrome.com/docs/lighthouse/performance/)?
- Could you set up a notification to let you know when a new deploy succeeded or failed?
{{PreviousMenu("Learn/Tools_and_testing/Understanding_client-side_tools/Introducing_complete_toolchain", "Learn/Tools_and_testing/Understanding_client-side_tools")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/understanding_client-side_tools | data/mdn-content/files/en-us/learn/tools_and_testing/understanding_client-side_tools/command_line/index.md | ---
title: Command line crash course
slug: Learn/Tools_and_testing/Understanding_client-side_tools/Command_line
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Understanding_client-side_tools/Overview","Learn/Tools_and_testing/Understanding_client-side_tools/Package_management", "Learn/Tools_and_testing/Understanding_client-side_tools")}}
In your development process, you'll undoubtedly be required to run some commands in the terminal (or on the "command line" β these are effectively the same thing). This article provides an introduction to the terminal, the essential commands you'll need to enter into it, how to chain commands together, and how to add your own command line interface (CLI) tools.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and <a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand what the terminal/command line is, what basic commands you should learn, and how to install new command line tools.
</td>
</tr>
</tbody>
</table>
## Welcome to the terminal
The terminal is a text interface for executing text-based programs. If you're running any tooling for web development there's a near-guaranteed chance that you'll have to pop open the command line and run some commands to use your chosen tools (you'll often see such tools referred to as **CLI tools** β command line interface tools).
A large number of tools can be used by typing commands into the command line; many come pre-installed on your system, and a huge number of others are installable from package registries.
Package registries are like app stores, but (mostly) for command line based tools and software.
We'll see how to install some tools later on in this chapter, and we'll learn more about package registries in the next chapter.
One of the biggest criticisms of the command line is that it lacks hugely in user experience.
Viewing the command line for the first time can be a daunting experience: a blank screen and a blinking cursor, with very little obvious help available on what to do.
On the surface, they're far from welcoming but there's a lot you can do with them, and we promise that, with a bit of guidance and practice, using them will get easier!
This is why we are providing this chapter β to help you get started in this seemingly unfriendly environment.
### Where did the terminal come from?
The terminal originates from around the 1950s-60s and its original form really doesn't resemble what we use today (for that we should be thankful). You can read a bit of the history on Wikipedia's entry for [Computer Terminal](https://en.wikipedia.org/wiki/Computer_terminal).
Since then, the terminal has remained a constant feature of all operating systems β from desktop machines to servers tucked away in the cloud, to microcomputers like the Raspberry PI Zero, and even to mobile phones. It provides direct access to the computer's underlying file system and low-level features, and is therefore incredibly useful for performing complex tasks rapidly, if you know what you are doing.
It is also useful for automation β for example, to write a command to update the titles of hundreds of files instantly, say from "ch01-xxxx.png" to "ch02-xxxx.png". If you updated the file names using your finder or explorer GUI app, it would take you a long time.
Anyway, the terminal is not going away anytime soon.
### What does the terminal look like?
Below you can see some of the different flavors of programs that are available that can get you to a terminal.
The next images show the command prompts available in Windows β there's a good range of options from the "cmd" program to "powershell" β which can be run from the start menu by typing the program name.

And below, you can see the macOS terminal application.

### How do you access the terminal?
Many developers today are using Unix-based tools (e.g. the terminal, and the tools you can access through it). Many tutorials and tools that exist on the web today support (and sadly assume) Unix-based systems, but not to worry β they are available on most systems. In this section, we'll look at how to get access to the terminal on your chosen system.
#### Linux/Unix
As hinted at above, Linux/Unix systems have a terminal available by default, listed among your Applications.
#### macOS
macOS has a system called Darwin that sits underneath the graphical user interface. Darwin is a Unix-like system, which provides the terminal, and access to the low-level tools. macOS Darwin mostly has parity with Unix, certainly good enough to not cause us any worries as we work through this article.
The terminal is available on macOS at Applications/Utilities/Terminal.
#### Windows
As with some other programming tools, using the terminal (or command line) on Windows has traditionally not been as simple or easy as on other operating systems. But things are getting better.
Windows has traditionally had its own terminal-like program called cmd ("the command prompt") for a long time, but this definitely doesn't have parity with Unix commands, and is equivalent to the old-style Windows DOS prompt.
Better programs exist for providing a terminal experience on Windows, such as Powershell ([see here to find installers](https://github.com/PowerShell/PowerShell)), and Gitbash (which comes as part of the [git for Windows](https://gitforwindows.org/) toolset).
However, the best option for Windows in the modern day is the Windows Subsystem for Linux (WSL) β a compatibility layer for running Linux operating systems directly from inside Windows 10, allowing you to run a "true terminal" directly on Windows, without needing a virtual machine.
This can be installed directly from the Windows store for free. You can find all the documentation you need in the [Windows Subsystem for Linux Documentation](https://docs.microsoft.com/windows/wsl/).

In terms of what option to choose on Windows, we'd strongly recommend trying to install the WSL. You could stick with the default command prompt (`cmd`), and many tools will work OK, but you'll find everything easier if you have better parity with Unix tools.
#### Side note: what's the difference between a command line and a terminal?
Generally, you'll find these two terms used interchangeably. Technically, a terminal is a software that starts and connects to a shell. A shell is your session and session environment (where things like the prompt and shortcuts might be customized). The command line is the literal line where you enter commands and the cursor blinks.
### Do you have to use the terminal?
Although there's a great wealth of tools available from the command line, if you're using tools like [Visual Studio Code](https://code.visualstudio.com/) there's also a mass of extensions that can be used as a proxy to use terminal commands without needing to use the terminal directly. However, you won't find a code editor extension for everything you want to do β you'll have to get some experience with the terminal eventually.
## Basic built-in terminal commands
Enough talk β let's start looking at some terminal commands! Out of the box, here are just a few of the things the command line can do, along with the names of relevant tools in each case:
- Navigate your computer's file system along with base-level tasks such as create, copy, rename, and delete:
- Move around your directory structure: `cd`
- Create directories: `mkdir`
- Create files (and modify their metadata): `touch`
- Copy files or directories: `cp`
- Move files or directories: `mv`
- Delete files or directories: `rm`
- Download files found at specific URLs: `curl`
- Search for fragments of text inside larger bodies of text: `grep`
- View a file's contents page by page: `less`, `cat`
- Manipulate and transform streams of text (for example changing all the instances of `<div>`s in an HTML file to `<article>`): `awk`, `tr`, `sed`
> **Note:** There are a number of good tutorials on the web that go much deeper into the command line β this is only a brief introduction!
Let's move forward and look at using a few of these tools on the command line. Before you go any further, open your terminal program!
### Navigation on the command line
When you visit the command line you will inevitably need to navigate to a particular directory to "do something". All the operating systems (assuming a default setup) will launch their terminal program in your "home" directory, and from there you're likely to want to move to a different place.
The `cd` command lets you Change Directory. Technically, cd isn't a program but a built-in. This means your operating system provides it out of the box, and also that you can't accidentally delete it β thank goodness! You don't need to worry too much about whether a command is built-in or not, but bear in mind that built-ins appear on all unix-based systems.
To change the directory, you type `cd` into your terminal, followed by the directory you want to move to. Assuming the directory is inside your home directory, you can use `cd Desktop` (see the screenshots below).

Try typing this into your system's terminal:
```bash
cd Desktop
```
If you want to move back up to the previous directory, you can use two dots:
```bash
cd ..
```
> **Note:** A very useful terminal shortcut is using the <kbd>tab</kbd> key to autocomplete names that you know are present, rather than having to type out the whole thing. For example, after typing the above two commands, try typing `cd D` and pressing <kbd>tab</kbd> β it should autocomplete the directory name `Desktop` for you, provided it is present in the current directory. Bear this in mind as you move forward.
If the directory you want to go to is nested deep, you need to know the path to get to it. This usually becomes easier as you get more familiar with the structure of your file system, but if you are not sure of the path you can usually figure it out with a combination of the `ls` command (see below), and by clicking around in your Explorer/Finder window to see where a directory is, relative to where you currently are.
For example, if you wanted to go to a directory called `src`, located inside a directory called `project`, located on the `Desktop`, you could type these three commands to get there from your home folder:
```bash
cd Desktop
cd project
cd src
```
But this a waste of time β instead, you can type one command, with the different items in the path separated by forward slashes, just like you do when specifying paths to images or other assets in CSS, HTML, or JavaScript code:
```bash
cd Desktop/project/src
```
Note that including a leading slash on your path makes the path absolute, for example `/Users/your-user-name/Desktop`. Omitting the leading slash as we've done above makes the path relative to your present working directory. This is exactly the same as you would see with URLs in your web browser. A leading slash means "at the root of the website", whereas omitting the slash means "the URL is relative to my current page".
> **Note:** On windows, you use backslashes instead of forward slashes, e.g. `cd Desktop\project\src` β this may seem really odd, but if you are interested in why, [watch this YouTube clip](https://www.youtube.com/watch?v=5T3IJfBfBmI) featuring an explanation by one of Microsoft's Principal engineers.
### Listing directory contents
Another built-in Unix command is `ls` (short for list), which lists the contents of the directory you're currently in. Note that this won't work if you're using the default Windows command prompt (`cmd`) β the equivalent there is `dir`.
Try running this now in your terminal:
```bash
ls
```
This gives you a list of the files and directories in your present working directory, but the information is really basic β you only get the name of each item present, not whether it is a file or a directory, or anything else. Fortunately, a small change to the command usage can give you a lot more information.
### Introducing command options
Most terminal commands have options β these are modifiers that you add onto the end of a command, which make it behave in a slightly different way. These usually consist of a space after the command name, followed by a dash, followed by one or more letters.
For example, give this a go and see what you get:
```bash
ls -l
```
In the case of `ls`, the `-l` (_dash ell_) option gives you a listing with one file or directory on each line, and a lot more information shown. Directories can be identified by looking for a letter "d" on the very left-hand side of the lines. Those are the ones we can `cd` into.
Below is a screenshot with a "vanilla" macOS terminal at the top, and a customized terminal with some extra icons and colors to keep it looking lively β both showing the results of running `ls -l`:

> **Note:** To find out exactly what options each command has available, you can look at its [man page](https://en.wikipedia.org/wiki/Man_page). This is done by typing the `man` command, followed by the name of the command you want to look up, for example `man ls`. This will open up the man page in the terminal's default text file viewer (for example, [`less`](<https://en.wikipedia.org/wiki/Less_(Unix)>) in my terminal), and you should then be able to scroll through the page using the arrow keys, or some similar mechanism. The man page lists all the options in great detail, which may be a bit intimidating to begin with, but at least you know it's there if you need it. Once you are finished looking through the man page, you need to quit out of it using your text viewer's quit command ("q" in `less`; you may have to search on the web to find it if it isn't obvious).
> **Note:** To run a command with multiple options at the same time, you can usually put them all in a single string after the dash character, for example `ls -lah`, or `ls -ltrh`. Try looking at the `ls` man page to work out what these extra options do!
Now that we've discussed two fundamental commands, have a little poke around your directory and see if you can navigate from one place to the next.
### Creating, copying, moving, removing
There are a number of other basic utility commands that you'll probably end up using quite a lot as you work with the terminal. They are pretty simple, so we won't explain them all in quite as much detail as the previous couple.
Have a play with them in a test directory you've created somewhere so that you don't accidentally delete anything important, using the example commands below for guidance:
- `mkdir` β this creates a new directory inside the current directory you are in, with the name you provide after the command name. For example, `mkdir my-awesome-website` will make a new directory called `my-awesome-website`.
- `rmdir` β removes the named directory, but only if it's empty. For example, `rmdir my-awesome-website` will remove the directory we created above. If you want to remove a directory that is not empty (and also remove everything it contains), then you can use the `-r` option (recursive), but this is dangerous. Make sure there is nothing you might need inside the directory later on, as it will be gone forever.
- `touch` β creates a new empty file, inside the current directory. For example, `touch mdn-example.md` creates a new empty file called `mdn-example.md`.
- `mv` β moves a file from the first specified file location to the second specified file location, for example `mv mdn-example.md mdn-example.txt` (the locations are written as file paths). This command moves a file called `mdn-example.md` in the current directory to a file called `mdn-example.txt` in the current directory. Technically the file is being moved, but from a practical perspective, this command is actually renaming the file.
- `cp` β similar in usage to `mv`, `cp` creates a copy of the file in the first location specified, in the second location specified. For example, `cp mdn-example.txt mdn-example.txt.bak` creates a copy of `mdn-example.txt` called `mdn-example.txt.bak` (you can of course call it something else if you wish).
- `rm` β removes the specified file. For example, `rm mdn-example.txt` deletes a single file called `mdn-example.txt`. Note that this delete is permanent and can't be undone via the recycle bin that you might have on your desktop user interface.
> **Note:** Many terminal commands allow you to use asterisks as "wild card" characters, meaning "any sequence of characters". This allows you to run an operation against a potentially large number of files at once, all of which match the specified pattern. As an example, `rm mdn-*` would delete all files beginning with `mdn-`. `rm mdn-*.bak` would delete all files that start with `mdn-` and end with `.bak`.
## Terminal β considered harmful?
We've alluded to this before, but to be clear β you need to be careful with the terminal. Simple commands do not carry too much danger, but as you start putting together more complex commands, you need to think carefully about what the command will do, and try testing them out first before you finally run them in the intended directory.
Let's say you had 1000 text files in a directory, and you wanted to go through them all and only delete the ones that have a certain substring inside the filename. If you are not careful, then you might end up deleting something important, losing you a load of your work in the process.
One good habit to get into is to write your terminal command out inside a text editor, figure out how you think it should look, and then make a backup copy of your directory and try running the command on that first, to test it.
Another good tip β if you're not comfortable trying terminal commands out on your own machine, a nice safe place to try them is over at [Glitch.com](https://glitch.com/). Along with being a great place to try out web development code, the projects also give you access to a terminal, so you can run all these commands directly in that terminal, safe in the knowledge that you won't break your own machine.

A great resource for getting a quick overview of specific terminal commands is [tldr.sh](https://tldr.sh/). This is a community-driven documentation service, similar to MDN, but specific to terminal commands.
In the next section let's step it up a notch (or several notches in fact) and see how we can connect tools together on the command line to really see how the terminal can be advantageous over the regular desktop user interface.
## Connecting commands together with pipes
The terminal really comes into its own when you start to chain commands together using the `|` (pipe) symbol. Let's look at a very quick example of what this means.
We've already looked at `ls`, which outputs the contents of the current directory:
```bash
ls
```
But what if we wanted to quickly count the number of files and directories inside the current directory? `ls` can't do that on its own.
There is another Unix tool available called `wc`. This counts the number of words, lines, characters, or bytes of whatever is inputted into it. This can be a text file β the below example outputs the number of lines in `myfile.txt`:
```bash
wc -l myfile.txt
```
But it can also count the number of lines of whatever output is **piped** into it. For example, the below command counts the number of lines outputted by the `ls` command (what it would normally print to the terminal if run on its own) and outputs that count to the terminal instead:
```bash
ls | wc -l
```
Since `ls` prints each file or directory on its own line, that effectively gives us a directory and file count.
So what is going on here? A general philosophy of (unix) command line tools is that they print text to the terminal (also referred to "printing to standard output" or `STDOUT`). A good deal of commands can also read content from streamed input (known as "standard input" or `STDIN`).
The pipe operator can _connect_ these inputs and outputs together, allowing us to build up increasingly more complex operations to suit our needs β the output from one command can become the input to the next command. In this case, `ls` would normally print its output to `STDOUT`, but instead `ls`'s output is being piped into `wc`, which takes that output as an input, counting the number of lines it contains, and prints that count to `STDOUT` instead.
## A slightly more complex example
Let's go through something a bit more complicated.
We will first try to fetch the contents of MDN's "fetch" page using the `curl` command (which can be used to request content from URLs), from `https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch`.
Try it now:
```bash
curl https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch
```
You won't get an output because the page has been redirected (to [/Web/API/fetch](/en-US/docs/Web/API/fetch)).
We need to explicitly tell `curl` to follow redirects using the `-L` flag.
Let's also look at the headers that `developer.mozilla.org` returns using `curl`'s `-I` flag, and print all the location redirects it sends to the terminal, by piping the output of `curl` into `grep` (we will ask `grep` to return all the lines that contain the word "location").
Try running the following (you'll see that there is just one redirect before we reach the final page):
```bash
curl https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch -L -I | grep location
```
Your output should look something like this (`curl` will first output some download counters and suchlike):
```bash
location: /en-US/docs/Web/API/fetch
```
Although contrived, we could take this result a little further and transform the `location:` line contents, adding the base origin to the start of each one so that we get complete URLs printed out.
For that, we'll add `awk` to the mix (which is a programming language akin to JavaScript or Ruby or Python, just a lot older!).
Try running this:
```bash
curl https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch -L -I | grep location | awk '{ print "https://developer.mozilla.org" $2 }'
```
Your final output should look something like this:
```bash
https://developer.mozilla.org/en-US/docs/Web/API/fetch
```
By combining these commands we've customized the output to show the full URLs that the Mozilla server is redirecting through when we request the `/docs/Web/API/WindowOrWorkerGlobalScope/fetch` URL.
Getting to know your system will prove useful in years to come β learn how these single serving tools work and how they can become part of your toolkit to solve niche problems.
## Adding powerups
Now we've had a look at some of the built-in commands your system comes equipped with, let's look at how we can install a third-party CLI tool and make use of it.
The vast ecosystem of installable tools for front-end web development currently exists mostly inside [npm](https://www.npmjs.com), a privately owned, package hosting service that works closely together with Node.js.
This is slowly expanding β you can expect to see more package providers as time goes on.
[Installing Node.js](https://nodejs.org/en/) also installs the npm command line tool (and a supplementary npm-centric tool called npx), which offers a gateway to installing additional command line tools. Node.js and npm work the same across all systems: macOS, Windows, and Linux.
Install npm on your system now, by going to the URL above and downloading and running a Node.js installer appropriate to your operating system. If prompted, make sure to include npm as part of the installation.

Although we'll look at a number of different tools in the next article onwards, we'll cut our teeth on [Prettier](https://prettier.io/).
Prettier is an opinionated code formatter that only has a "few options".
Fewer options tends to mean simpler.
Given how tooling can sometimes get out of hand in terms of complexity, "few options" can be very appealing.
### Where to install our CLI tools?
Before we dive into installing Prettier, there's a question to answer β "where should we install it?"
With `npm` we have the choice of installing tools globally β so we can access them anywhere β or locally to the current project directory.
There are pros and cons each way β and the following lists of pros and cons for installing globally are far from exhaustive.
**Pros of installing globally:**
- Accessible anywhere in your terminal
- Only install once
- Uses less disk space
- Always the same version
- Feels like any other unix command
**Cons of installing globally:**
- May not be compatible with your project's codebase
- Other developers in your team won't have access to these tools, for example if you are sharing the codebase over a tool like git.
- Related to the previous point, it makes project code harder to replicate (if you install your tools locally, they can be set up as dependencies and installed with <code>npm install</code>).
Although the _cons_ list is shorter, the negative impact of global installing is potentially much larger than the benefits.
Here we'll install locally, but feel free to install globally once you understand the relative risks.
### Installing Prettier
Prettier is an opinionated code formatting tool for front-end developers, focusing on JavaScript-based languages and adding support for HTML, CSS, SCSS, JSON, and more.
Prettier can:
- Save the cognitive overhead of getting the style consistent manually across all your code files; Prettier can do this for you automatically.
- Help newcomers to web development format their code in best-practice fashion.
- Be installed on any operating system and even as a direct part of project tooling, ensuring that colleagues and friends who work on your code use the code style you're using.
- Be configured to run upon save, as you type, or even before publishing your code (with additional tooling that we'll see later on in the module).
For this article, we will install Prettier locally, as suggested in the [Prettier installation guide](https://prettier.io/docs/en/install.html)
Once you've installed node, open up the terminal and run the following command to install Prettier:
```bash
npm install prettier
```
You can now run the file locally using the [npx](https://docs.npmjs.com/cli/commands/npx) tool.
Running the command without any arguments, as with many other commands, will offer up usage and help information.
Try this now:
```bash
npx prettier
```
Your output should look something like this:
```bash
Usage: prettier [options] [file/glob ...]
By default, output is written to stdout.
Stdin is read if it is piped to Prettier and no files are given.
β¦
```
It's always worth at the very least skimming over the usage information, even if it is long.
It'll help you to understand better how the tool is intended to be used.
> **Note:** If you have not first installed Prettier locally, then running `npx prettier` will download and run the latest version of Prettier all in one go _just for that command_.
> While that might sound great, new versions of Prettier may slightly modify the output.
> You want to install it locally so that you are fixing the version of Prettier that you are using for formatting until you are ready to change it.
### Playing with Prettier
Let's have a quick play with Prettier, so you can see how it works.
First of all, create a new directory somewhere on your file system that is easy to find. Maybe a directory called `prettier-test` on your `Desktop`.
Now save the following code in a new file called `index.js`, inside your test directory:
```js-nolint
const myObj = {
a:1,b:{c:2}}
function printMe(obj){console.log(obj.b.c)}
printMe(myObj)
```
We can run Prettier against a codebase to just check if our code wants adjusting. `cd` into your directory, and try running this command:
```bash
npx prettier --check index.js
```
You should get an output along the lines of:
```bash
Checking formatting...
index.js
Code style issues found in the above file(s). Forgot to run Prettier?
```
So, there's some code styles that can be fixed. No problem. Adding the `--write` option to the `prettier` command will fix those up, leaving us to focus on actually writing useful code.
Now try running this version of the command:
```bash
npx prettier --write index.js
```
You'll get an output like this
```bash
Checking formatting...
index.js
Code style issues fixed in the above file(s).
```
But more importantly, if you look back at your JavaScript file you'll find it has been reformatted to something like this:
```js
const myObj = {
a: 1,
b: { c: 2 },
};
function printMe(obj) {
console.log(obj.b.c);
}
printMe(myObj);
```
Depending on your workflow (or the workflow that you pick) you can make this an automated part of your process. Automation is really where tools excel; our personal preference is the kind of automation that "just happens" without having to configure anything.
With Prettier there's a number of ways automation can be achieved and though they're beyond the scope of this article, there's some excellent resources online to help (some of which have been linked to). You can invoke Prettier:
- Before you commit your code into a git repository using [Husky](https://github.com/typicode/husky).
- Whenever you hit "save" in your code editor, be it [VS Code](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode), or [Sublime Text](https://packagecontrol.io/packages/JsPrettier).
- As part of continuous integration checks using tools like [GitHub Actions](https://github.com/features/actions).
Our personal preference is the second one β while using say VS Code, Prettier kicks in and cleans up any formatting it needs to do every time we hit save. You can find a lot more information about using Prettier in different ways in the [Prettier docs](https://prettier.io/docs/en/).
## Other tools to play with
If you want to play with a few more tools, here's a brief list that are fun to try out:
- [`bat`](https://github.com/sharkdp/bat) β A "nicer" `cat` (`cat` is used to print the contents of files).
- [`prettyping`](https://denilson.sa.nom.br/prettyping/) β `ping` on the command line, but visualized (`ping` is a useful tool to check if a server is responding).
- [`htop`](https://htop.dev/) β A process viewer, useful for when something is making your CPU fan behave like a jet engine and you want to identify the offending program.
- [`tldr`](https://tldr.sh/#installation) β mentioned earlier in this chapter, but available as a command line tool.
Note that some of the above suggestions may need installing using npm, like we did with Prettier.
## Summary
That brings us to the end of our brief tour of the terminal/command line. Next up we'll be looking in more detail at package managers, and what we can do with them.
{{PreviousMenuNext("Learn/Tools_and_testing/Understanding_client-side_tools/Overview","Learn/Tools_and_testing/Understanding_client-side_tools/Package_management", "Learn/Tools_and_testing/Understanding_client-side_tools")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/understanding_client-side_tools | data/mdn-content/files/en-us/learn/tools_and_testing/understanding_client-side_tools/package_management/index.md | ---
title: Package management basics
slug: Learn/Tools_and_testing/Understanding_client-side_tools/Package_management
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Understanding_client-side_tools/Command_line","Learn/Tools_and_testing/Understanding_client-side_tools/Introducing_complete_toolchain", "Learn/Tools_and_testing/Understanding_client-side_tools")}}
In this article, we'll look at package managers in some detail to understand how we can use them in our own projects β to install project tool dependencies, keep them up-to-date, and more.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand what package managers and package repositories are, why
they are needed, and the basics of how to use them.
</td>
</tr>
</tbody>
</table>
## A dependency in your project
A **dependency** is a third-party bit of software that was probably written by someone else and ideally solves a single problem for you. A web project can have any number of dependencies, ranging from none to many, and your dependencies might include sub-dependencies that you didn't explicitly install β your dependencies may have their own dependencies.
A simple example of a useful dependency that your project might need is some code to calculate relative dates as human-readable text. You could certainly code this yourself, but there's a strong chance that someone else has already solved this problem β why waste time reinventing the wheel? Moreover, a reliable third-party dependency will likely have been tested in a lot of different situations, making it more robust and cross-browser compatible than your own solution.
A project dependency can be an entire JavaScript library or framework β such as React or Vue β or a very small utility like our human-readable date library, or it can be a command line tool such as Prettier or ESLint, which we talked about in previous articles.
Without modern build tools, dependencies like this might be included in your project using a simple [`<script>`](/en-US/docs/Web/HTML/Element/script) element, but this might not work right out of the box and you will likely need some modern tooling to bundle your code and dependencies together when they are released on the web. A bundle is a term that's generally used to refer to a single file on your web server that contains all the JavaScript for your software β typically compressed as much as possible to help reduce the time it takes to get your software downloaded and displayed in your visitors' browser.
In addition, what happens if you find a better tool that you want to use instead of the current one, or a new version of your dependency is released that you want to update to? This is not too painful for a couple of dependencies, but in larger projects with many dependencies, this kind of thing can become really challenging to keep track of. It makes more sense to use a **package manager** such as npm, as this will guarantee that the code is added and removed cleanly, as well as a host of other advantages.
## What exactly is a package manager?
We've met [npm](https://www.npmjs.com/) already, but stepping back from npm itself, a package manager is a system that will manage your project dependencies.
The package manager will provide a method to install new dependencies (also referred to as "packages"), manage where packages are stored on your file system, and offer capabilities for you to publish your own packages.
In theory, you may not need a package manager and you could manually download and store your project dependencies, but a package manager will seamlessly handle installing and uninstalling packages. If you didn't use one, you'd have to manually handle:
- Finding all the correct package JavaScript files.
- Checking them to make sure they don't have any known vulnerabilities.
- Downloading them and putting them in the correct locations in your project.
- Writing the code to include the package(s) in your application (this tends to be done using [JavaScript modules](/en-US/docs/Web/JavaScript/Guide/Modules), another subject that is worth reading up on and understanding).
- Doing the same thing for all of the packages' sub-dependencies, of which there could be tens, or hundreds.
- Removing all the files again if you want to remove the packages.
In addition, package managers handle duplicate dependencies (something that becomes important and common in front-end development).
In the case of npm (and JavaScript- and Node-based package managers) you have two options for where you install your dependencies. As we touched on in the previous article, dependencies can be installed globally or locally to your project. Although there tend to be more pros for installing globally, the pros for installing locally are more important β such as code portability and version locking.
For example, if your project relied on Webpack with a certain configuration, you'd want to ensure that if you installed that project on another machine or returned to it much later on, the configuration would still work. If a different version of Webpack was installed, it may not be compatible. To mitigate this, dependencies are installed locally to a project.
To see local dependencies really shine, all you need to do is try to download and run an existing project β if it works and all the dependencies work right out of the box, then you have local dependencies to thank for the fact that the code is portable.
> **Note:** npm is not the only package manager available. A successful and popular alternative package manager is [Yarn](https://yarnpkg.com/). Yarn resolves the dependencies using a different algorithm that can mean a faster user experience. There are also a number of other emerging clients, such as [pnpm](https://pnpm.js.org/).
## Package registries
For a package manager to work, it needs to know where to install packages from, and this comes in the form of a package registry. The registry is a central place where a package is published and thus can be installed from. npm, as well as being a package manager, is also the name of the most commonly-used package registry for JavaScript packages. The npm registry exists at [npmjs.com](https://www.npmjs.com/).
npm is not the only option. You could manage your own package registry β products like [Microsoft Azure](https://azure.microsoft.com/) allow you to create proxies to the npm registry (so you can override or lock certain packages), [GitHub also offers a package registry service](https://github.com/features/packages), and there will be likely more options appearing as time goes on.
What is important is that you ensure you've chosen the best registry for you. Many projects will use npm, and we'll stick to this in our examples throughout the rest of the module.
## Using the package ecosystem
Let's run through an example to get you started with using a package manager and registry to install a command line utility.
[Parcel](https://parceljs.org/) is another tool that developers commonly use in their development process. Parcel is clever in that it can watch the contents of our code for calls to dependencies and automatically installs any dependencies it sees that our code needs. It can also automatically build our code.
### Setting up the app as an npm package
First of all, create a new directory to store our experimental app in, somewhere sensible that you'll find again. We'll call it parcel-experiment, but you can call it whatever you like:
```bash
mkdir parcel-experiment
cd parcel-experiment
```
Next, let's initialise our app as an npm package, which creates a config file β `package.json` β that allows us to save our configuration details in case we want to recreate this environment later on, or even publish the package to the npm registry (although this is somewhat beyond the scope of this article).
Type the following command, making sure you are inside the `parcel-experiment` directory:
```bash
npm init
```
You will now be asked some questions; npm will then create a default `package.json` file based on the answers:
- `name`: A name to identify the app. Just press
<kbd>Return</kbd>
to accept the default `parcel-experiment`.
- `version`: The starting version number for the app. Again, just press
<kbd>Return</kbd>
to accept the default `1.0.0`.
- `description`: A quick description of the app's purpose. Type in something really simple, like "A simple npm package to learn about using npm", then press
<kbd>Return</kbd>
.
- `entry point`: This will be the top-level JavaScript file of the app. The default `index.js` is fine for now β press
<kbd>Return</kbd>
.
- `test command`, `git repository`, and `keywords`: press
<kbd>Return</kbd>
to leave each of these blank for now.
- `author`: The author of the project. Type your own name, and press
<kbd>Return</kbd>
.
- `license`: The license to publish the package under. Press
<kbd>Return</kbd>
to accept the default for now.
Press <kbd>Return</kbd> one more time to accept these settings.
Go into your `parcel-experiment` directory and you should now find you've got a package.json file. Open it up and it should look something like this:
```json
{
"name": "parcel-experiment",
"version": "1.0.0",
"description": "A simple npm package to learn about using npm",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Chris Mills",
"license": "ISC"
}
```
So this is the config file that defines your package. This is good for now, so let's move on.
### Installing parcel
Run the following command to install Parcel locally:
```bash
npm install parcel-bundler
```
Once that's done _All The Things_, we're now ready for some "modern client-side development" (which really means using build tools to make the developer experience a little easier). First of all however, take another look at your package.json file. You'll see that npm has added a new field, dependencies:
```json
"dependencies": {
"parcel-bundler": "^1.12.4"
}
```
This is part of the npm magic β if in the future you move your codebase to another location, on another machine, you can recreate the same setup by running the command `npm install`, and npm will look at the dependencies and install them for you.
One disadvantage is that Parcel is only available inside our `parcel-experiment` app; you won't be able to run it in a different directory. But the advantages outweigh the disadvantages.
### Setting up our example app
Anyway, on with the setup.
Parcel expects an `index.html` and an `index.js` file to work with, but otherwise, it is very unopinionated about how you structure your project. Other tools can be very different, but at least Parcel makes it easy for our initial experiment.
So now we need to add an `index.html` file to our working directory. Create `index.html` in your test directory, and give it the following contents:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>My test page</title>
</head>
<body>
<script src="./index.js"></script>
</body>
</html>
```
Next, we need to add an `index.js` file in the same directory as `index.html`. For now, `index.js` can be empty; it just needs to exist. Create this now.
### Having fun with Parcel
Now we'll run our newly installed Parcel tool. In your terminal, run the following command:
```bash
npx parcel index.html
```
You should see something like this printed in your terminal:
```bash
Server running at http://localhost:1234
β¨ Built in 193ms.
```
> **Note:** If you have trouble with the terminal returning a "command not found" type error, try running the above command with the `npx` utility, i.e. `npx parcel index.html`.
Now we're ready to benefit from the full JavaScript package ecosystem. For a start, there is now a local web server running at `http://localhost:1234`. Go there now and you'll not see anything for now, but what is cool is that when you do make changes to your app, Parcel will rebuild it and refresh the server automatically so you can instantly see the effect your update had.
Now for some page content. Let's say we want to show human-readable relative dates, such as "2 hours ago", "4 days ago" and so on. The [`date-fns`](https://date-fns.org/) package's `formatDistanceToNow()` method is useful for this (there's other packages that do the same thing too).
In the `index.js` file, add the following code and save it:
```js
import { formatDistanceToNow } from "date-fns";
const date = "1996-09-13 10:00:00";
document.body.textContent = `${formatDistanceToNow(new Date(date))} ago`;
```
Go back to `http://localhost:1234` and you'll see how long ago it is since the author turned 18.
What's particularly special about the code above is that it is using the `formatDistanceToNow()` function from the `date-fns` package, which we didn't install! Parcel has spotted that you need the module, searched for it in the `npmjs.com` package registry, and installed it locally for us, automatically. You can prove this by looking in our `package.json` file again β you'll see that the `dependencies` field has been updated for us:
```json
"dependencies": {
"date-fns": "^2.12.0",
"parcel-bundler": "^1.12.4"
}
```
Parcel has also added the files required for someone else to pick up this project and install any dependencies that we've used. If you take a look in the directory you ran the `parcel` command in, you'll find a number of new files; the most interesting of which are:
- `node_modules`: The dependency files of Parcel and date-fns.
- `dist`: The distribution directory β these are the automatically packaged, minified files Parcel has built for us, and the files it is serving at `localhost:1234`. These are the files you would upload to your web server when releasing the site online for public consumption.
So long as we know the package name, we can use it in our code and Parcel will go off, fetch, and install (actually "copy") the package into our local directory (under `node_modules`).
### Building our code for production
However, this code is not ready for production. Most build tooling systems will have a "development mode" and a "production mode". The important difference is that a lot of the helpful features you will use in development are not needed in the final site, so will be stripped out for production, e.g. "hot module replacement", "live reloading", and "uncompressed and commented source code". Though far from exhaustive, these are some of the common web development features that are very helpful at the development stage but are not very useful in production. In production, they will just bloat your site.
Now stop the previous Parcel command using <kbd>Ctrl</kbd> + <kbd>C</kbd>.
We can now prepare our bare bones example site for an imaginary deployment. Parcel provides an additional command to generate files that are suited to publication, making bundles (mentioned earlier) with the build option.
Run the following command:
```bash
npx parcel build index.html
```
You should see an output like so:
```bash
β¨ Built in 9.35s.
dist/my-project.fb76efcf.js.map 648.58 KB 64ms
dist/my-project.fb76efcf.js 195.74 KB 8.43s
dist/index.html 288 B 806ms
```
Again, the destination for our production files is the `dist` directory.
### Reducing your app's file size
However, as with all tools that "help" developers there's often a tradeoff. In this particular case, it's the file size. The JavaScript bundle my-project.fb76efcf.js is a whopping 195K β very large, given that all it does is print a line of text. Sure, there's some calculation, but we definitely don't need 195K worth of JavaScript to do this!
When you use development tooling it's worth questioning whether they're doing the right thing for you. In this case, the bundle is nearly 200K because it has in fact included the entire `date-fns` library, not just the function we're using.
If we had avoided any development tools and pointed a `<script src="">` element to a hosted version of `date-fns`, roughly the same thing would have happened β all of the library would be downloaded when our example page is loaded in a browser.
However, this is where development tooling has a chance to shine. Whilst the tooling is on our machine, we can ask the software to inspect our use of the code and only include the functions that we're actually using in production β a process known as "Tree Shaking".
This makes a lot of sense as we want to reduce file size and thus make our app load as quickly as possible. Different tooling will let you tree shake in different ways.
Although the list grows by the month, there are three main offerings for tools that generate bundles from our source code: Webpack, [Rollup](https://rollupjs.org/guide/en/), and Parcel. There will be more available than this, but these are popular ones:
- The RollUp tool offers tree shaking and code splitting as its core features.
- Webpack requires some configuration (though "some" might be understating the complexity of some developers' Webpack configurations).
- In the case of Parcel (prior to Parcel version 2), there's a special flag required β `--experimental-scope-hoisting` β which will tree shake while building.
Let's stick with Parcel for now, given that we've already got it installed. Try running the following command:
```bash
npx parcel build index.html --experimental-scope-hoisting
```
You'll see that this makes a huge difference:
```bash
β¨ Built in 7.87s.
dist/my-project.86f8a5fc.js 10.34 KB 7.17s
dist/index.html 288 B 753ms
```
Now the bundle is approximately 10K. Much better.
If we were to release this project to a server, we would only release the files in the `dist` folder. Parcel has automatically handled all the filename changes for us. We recommend having a look at the source code in `dist/index.html` just so you can see what changes Parcel has performed automatically.
> **Note:** At the time of writing, Parcel 2 had not been released. However when it does, these commands will all still work because the authors of Parcel have had the good sense to name the tool slightly differently. To install Parcel 1.x you have to install `parcel-bundler`, but parcel 2.x is called `parcel`.
There's a lot of tools available and the JavaScript package ecosystem is growing at an unprecedented rate, which has pros and cons. There's improvements being made all the time and the choice, for better or worse, is constantly increasing. Faced with the overwhelming choice of tooling, probably the most important lesson is to learn what the tool you select is capable of.
## A rough guide to package manager clients
This tutorial installed the Parcel package using npm, but as mentioned earlier on there are some alternatives. It's worth at least knowing they exist and having some vague idea of the common commands across the tools. You've already seen some in action, but let's look at the others.
The list will grow over time, but at the time of writing, the following main package managers are available:
- npm at [npmjs.org](https://www.npmjs.com/)
- pnpm at [pnpm.js.org](https://pnpm.js.org/)
- Yarn at [yarnpkg.com](https://yarnpkg.com/)
npm and pnpm are similar from a command line point of view β in fact, pnpm aims to have full parity over the argument options that npm offers. It differs in that it uses a different method for downloading and storing the packages on your computer, aiming to reduce the overall disk space required.
Where npm is shown in the examples below, pnpm can be swapped in and the command will work.
Yarn is often thought to be quicker than npm in terms of the installation process (though your mileage may vary). This is important to developers because there can be a significant amount of time wasted on waiting for dependencies to install (and copy to the computer).
> **Note:** The npm package manager is **not** required to install packages from the npm registry, even though they share the same name. pnpm and Yarn can consume the same `package.json` format as npm, and can install any package from the npm and other package registries.
Let's review the common actions you'll want to perform with package managers.
### Initialise a new project
```bash
npm init
yarn init
```
As shown above, this will prompt and walk you through a series of questions to describe your project (name, license, description, and so on) then generate a `package.json` for you that contains meta-information about your project and its dependencies.
### Installing dependencies
```bash
npm install date-fns
yarn add date-fns
```
We also saw `install` in action above. This would directly add the `date-fns` package to the working directory in a subdirectory called `node_modules`, along with `date-fns`'s own dependencies.
By default, this command will install the latest version of `date-fns`, but you can control this too. You can ask for `date-fns@1`, which gives you the latest 1.x version (which is 1.30.1). Or you could try `date-fns@^2.3.0`, which means the latest version after or including 2.3.0 (2.8.1 at the time of writing).
### Updating dependencies
```bash
npm update
yarn upgrade
```
This will look at the currently installed dependencies and update them, if there is an update available, within the range that's specified in the package.
The range is specified in the version of the dependency in your `package.json`, such as `date-fns@^2.0.1` β in this case, the caret character `^` means all minor and patch releases after and including 2.0.1, up to but excluding 3.0.0.
This is determined using a system called [semver](https://semver.org/), which might look a bit complicated from the documentation but can be simplified by considering only the summary information and that a version is represented by `MAJOR.MINOR.PATCH`, such as 2.0.1 being major version 2 with patch version 1. An excellent way to try out semver values is to use the [semver calculator](https://semver.npmjs.com/).
It's important to remember that `npm update` will not upgrade the dependencies to beyond the range defined in the `package.json` β to do this you will need to install that version specifically.
### Audit for vulnerabilities
```bash
npm audit
yarn audit
```
This will check all of the dependency tree for your project and run the specific versions you're using against a vulnerability database and notify you if there are potential vulnerable packages in your project.
A good starting point for learning about vulnerabilities is the [Snyk project](https://snyk.io/), which covers both JavaScript packages and other programming languages.
### Checking on a dependency
```bash
npm ls date-fns
yarn why date-fns
```
This command will show what version of a dependency is installed and how it came to be included in your project. It's possible that another, top-level, package could have pulled in `date-fns`. It's equally possible (and not ideal) that you have multiple versions of a package in your project (this has been seen many times over with the [lodash](https://lodash.com/) package, as it's so useful).
Although the package manager will do its best to deduplicate packages you may want to investigate exactly which version is installed.
### More commands
You can find out more about the individual commands for [npm](https://docs.npmjs.com/cli-documentation/) and [yarn](https://classic.yarnpkg.com/en/docs/cli/) online. Again, [pnpm](https://pnpm.io/cli/add) commands will have parity with npm, with a handful of additions.
## Making your own commands
The package managers also support creating your own commands and executing them from the command line. For instance, we could create the following command:
```bash
npm run dev
# or yarn run dev
```
This would run a custom script for starting our project in "development mode". In fact, we regularly include this in all projects as the local development setup tends to run slightly differently to how it would run in production.
If you tried running this in your Parcel test project from earlier it would (likely) claim the "dev script is missing". This is because npm, Yarn (and the like) are looking for a property called dev in the `scripts` property of your `package.json` file.
Parcel can run a development server using the command `parcel serve filename.html`, and we'd like to use that often during our development.
So, let's create a custom shorthand command β "dev" β in our `package.json`.
If you followed the tutorial from earlier, you should have a `package.json` file inside your parcel-experiment directory. Open it up, and its `scripts` member should look like this:
```json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
},
```
Update it so that it looks like this, and save the file:
```json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "parcel serve index.html"
},
```
We've added a custom `dev` command as an npm script.
Now try running the following in your terminal, making sure you are inside the `parcel-experiment` directory:
```bash
npm run dev
```
This should start Parcel and serve up your `index.html` at the local development server, as we saw before:
```bash
Server running at http://localhost:1234
β¨ Built in 5.48s.
```
In addition, the npm (and yarn) commands are clever in that they will search for command line tools that are locally installed to the project before trying to find them through conventional methods (where your computer will normally store and allow software to be found). You can [learn more about the technical intricacies of the `run` command](https://docs.npmjs.com/cli/run-script/), although in most cases your own scripts will run just fine.
You can add all kinds of things to the `scripts` property that help you do your job. We certainly have, and [others have too](https://github.com/facebook/create-react-app/blob/c5b96c2853671baa3f1f297ec3b36d7358898304/package.json#L6).
## Summary
This brings us to the end of our tour of package managers. Our next move is to build up a sample toolchain, putting all that we've learnt so far into practice.
{{PreviousMenuNext("Learn/Tools_and_testing/Understanding_client-side_tools/Command_line","Learn/Tools_and_testing/Understanding_client-side_tools/Introducing_complete_toolchain", "Learn/Tools_and_testing/Understanding_client-side_tools")}}
## See also
- [npm scripts reference](https://docs.npmjs.com/cli/v8/using-npm/scripts/)
- [package.json reference](https://docs.npmjs.com/cli/v8/configuring-npm/package-json/)
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/understanding_client-side_tools | data/mdn-content/files/en-us/learn/tools_and_testing/understanding_client-side_tools/overview/index.md | ---
title: Client-side tooling overview
slug: Learn/Tools_and_testing/Understanding_client-side_tools/Overview
page-type: learn-module-chapter
---
{{LearnSidebar}}{{NextMenu("Learn/Tools_and_testing/Understanding_client-side_tools/Command_line", "Learn/Tools_and_testing/Understanding_client-side_tools")}}
In this article, we provide an overview of modern web tooling, what kinds of tools are available and where you'll meet them in the lifecycle of web app development, and how to find help with individual tools.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To understand what types of client-side tooling there are, and how to
find tools and get help with them.
</td>
</tr>
</tbody>
</table>
## Overview of modern tooling
Writing software for the web has become more sophisticated through the ages. Although it is still entirely reasonable to write HTML, CSS, and JavaScript "by hand" there is now a wealth of tools that developers can use to speed up the process of building a website, or app.
There are some extremely well-established tools that have become common "household names" amongst the development community, and new tools are being written and released every day to solve specific problems. You might even find yourself writing a piece of software to aid your own development process, to solve a specific problem that existing tools don't already seem to handle.
It is easy to become overwhelmed by the sheer number of tools that can be included in a single project. Equally, a single configuration file for a tool like [Webpack](https://webpack.js.org/) can be hundreds of lines long, most of which are magical incantations that seem to do the job but which only a master engineer will fully understand!
From time to time, even the most experienced of web developers get stuck on a tooling problem; it is possible to waste hours attempting to get a tooling pipeline working before even touching a single line of application code. If you have found yourself struggling in the past, then don't worry β you are not alone.
In these articles, we won't answer every question about web tooling, but we will provide you with a useful starting point of understanding the fundamentals, which you can then build from. As with any complex topic, it is good to start small, and gradually work your way up to more advanced uses.
## The modern tooling ecosystem
Today's modern developer tooling ecosystem is huge, so it's useful to have a broad idea of what main problems the tools are solving. If you jump on your favorite search engine and look for "front-end developer tools" you're going to hit a huge spectrum of results ranging from text editors, to browsers, to the type of pens you can use to take notes.
Though your choice of code editor is certainly a tooling choice, this series of articles will go beyond that, focusing on developer tools that help you produce web code more efficiently.
From a high-level perspective, you can put client-side tools into the following three broad categories of problems to solve:
- **Safety net** β Tools that are useful during your code development.
- **Transformation** β Tools that transform code in some way, e.g. turning an intermediate language into JavaScript that a browser can understand.
- **Post-development** β Tools that are useful after you have written your code, such as testing and deployment tools.
Let's look at each one of these in more detail.
### Safety net
These are tools that make the code you write a little better.
This part of the tooling should be specific to your own development environment, though it's not uncommon for companies to have some kind of policy or pre-baked configuration available to install so that all their developers are using the same processes.
This includes anything that makes your development process easier for generating stable and reliable code. Safety net tooling should also help you either prevent mistakes or correct mistakes automatically without having to build your code from scratch each time.
A few very common safety net tool types you will find being used by developers are as follows.
#### Linters
**Linters** are tools that check through your code and tell you about any errors that are present, what error types they are, and what code lines they are present on. Often linters can be configured to not only report errors, but also report any violations of a specified style guide that your team might be using (for example code that is using the wrong number of spaces for indentation, or using [template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals) rather than regular string literals).
[ESLint](https://eslint.org/) is the industry standard JavaScript linter β a highly configurable tool for catching potential syntax errors and encouraging "best practices" throughout your code. Some companies and projects have also [shared their ESLint configs](https://www.npmjs.com/search?q=keywords:eslintconfig).
You can also find linting tools for other languages, such as [csslint](http://csslint.net/).
Also well-worth looking at is [webhint](https://webhint.io/), a configurable, open-source linter for the web that surfaces best practices including approaches to accessibility, performance, cross-browser compatibility via [MDN's browser compatibility data](https://github.com/mdn/browser-compat-data), security, testing for PWAs, and more. It is available as a [Node.js command-line tool](https://webhint.io/docs/user-guide/) and a [VS Code extension](https://marketplace.visualstudio.com/items?itemName=webhint.vscode-webhint).
#### Source code control
Also known as **version control systems** (VCS), **source code control** is essential for backing work up and working in teams. A typical VCS involves having a local version of the code that you make changes to. You then "push" changes to a "master" version of the code inside a remote repository stored on a server somewhere. There is usually a way of controlling and coordinating what changes are made to the "master" copy of the code, and when, so a team of developers doesn't end up overwriting each other's work all the time.
[Git](https://git-scm.com/) is the source code control system that most people use these days. It is primarily accessed via the command line but can be accessed via friendly user interfaces. With your code in a git repository, you can push it to your own server instance, or use a hosted source control website such as [GitHub](https://github.com/), [GitLab](https://about.gitlab.com/), or [BitBucket](https://bitbucket.org/product/features).
We'll be using GitHub in this module. You can find more information about it at [Git and GitHub](/en-US/docs/Learn/Tools_and_testing/GitHub).
#### Code formatters
Code formatters are somewhat related to linters, except that rather than point out errors in your code, they usually tend to make sure your code is formatted correctly, according to your style rules, ideally automatically fixing errors that they find.
[Prettier](https://prettier.io/) is a very popular example of a code formatter, which we'll make use of later on in the module.
#### Bundlers/packagers
These are tools that get your code ready for production, for example by "tree-shaking" to make sure only the parts of your code libraries that you are actually using are put into your final production code, or "minifying" to remove all the whitespace in your production code, making it as small as possible before it is uploaded to a server.
[Parcel](https://parceljs.org/) is a particularly clever tool that fits into this category β it can do the above tasks, but also helps to package assets like HTML, CSS, and image files into convenient bundles that you can then go on to deploy, and also adds dependencies for you automatically whenever you try to use them. It can even handle some code transformation duties for you.
[Webpack](https://webpack.js.org/) is another very popular packaging tool that does similar things.
### Transformation
This stage of your web app lifecycle typically allows you to code in either "future code" (such as the latest CSS or JavaScript features that might not have native support in browsers yet) or code using another language entirely, such as [TypeScript](https://www.typescriptlang.org/). Transformation tools will then generate browser-compatible code for you, to be used in production.
Generally, web development is thought of as three languages: [HTML](/en-US/docs/Learn/HTML), [CSS](/en-US/docs/Learn/CSS), and [JavaScript](/en-US/docs/Learn/JavaScript), and there are transformation tools for all of these languages. Transformation offers two main benefits (amongst others):
1. The ability to write code using the latest language features and have that transformed into code that works on everyday devices. For example, you might want to write JavaScript using cutting-edge new language features, but still have your final production code work on older browsers that don't support those features. Good examples here include:
- [Babel](https://babeljs.io/): A JavaScript compiler that allows developers to write their code using cutting-edge JavaScript, which Babel then takes and converts into old-fashioned JavaScript that more browsers can understand. Developers can also write and publish [plugins for Babel](https://babeljs.io/docs/en/plugins).
- [PostCSS](https://postcss.org/): Does the same kind of thing as Babel, but for cutting-edge CSS features. If there isn't an equivalent way to do something using older CSS features, PostCSS will install a JavaScript polyfill to emulate the CSS effect you want.
2. The option to write your code in an entirely different language and have it transformed into a web-compatible language. For example:
- [Sass/SCSS](https://sass-lang.com/): This CSS extension allows you to use variables, nested rules, mixins, functions, and many other features, some of which are available in native CSS (such as variables), and some of which aren't.
- [TypeScript](https://www.typescriptlang.org/): TypeScript is a superset of JavaScript that offers a bunch of additional features. The TypeScript compiler converts TypeScript code to JavaScript when building for production.
- Frameworks such as [React](https://react.dev/), [Ember](https://emberjs.com/), and [Vue](https://vuejs.org/): Frameworks provide a lot of functionality for free and allow you to use it via custom syntax built on top of vanilla JavaScript. In the background, the framework's JavaScript code works hard to interpret this custom syntax and render it as a final web app.
### Post development
Post-development tooling ensures that your software makes it to the web and continues to run. This includes the deployment processes, testing frameworks, auditing tools, and more.
This stage of the development process is one that you want the least amount of active interaction with so that once it is configured, it runs mostly automatically, only popping up to say hello if something has gone wrong.
#### Testing tools
These generally take the form of a tool that will automatically run tests against your code to make sure it is correct before you go any further (for example, when you attempt to push changes to a GitHub repo). This can include linting, but also more sophisticated procedures like unit tests, where you run part of your code, making sure they behave as they should.
- Frameworks for writing tests include [Jest](https://jestjs.io/), [Mocha](https://mochajs.org/), and [Jasmine](https://jasmine.github.io/).
- Automated test running and notification systems include [Travis CI](https://travis-ci.org/), [Jenkins](https://www.jenkins.io/), [Circle CI](https://circleci.com/), and [others](https://en.wikipedia.org/wiki/List_of_build_automation_software#Continuous_integration).
#### Deployment tools
Deployment systems allow you to get your website published, are available for both static and dynamic sites, and commonly tend to work alongside testing systems. For example, a typical toolchain will wait for you to push changes to a remote repo, run some tests to see if the changes are OK, and then if the tests pass, automatically deploy your app to a production site.
[Netlify](https://www.netlify.com/) is one of the most popular deployment tools right now, but others include [Vercel](https://vercel.com/) and [GitHub Pages](https://pages.github.com/).
#### Others
There are several other tool types available to use in the post-development stage, including [Code Climate](https://codeclimate.com/) for gathering code quality metrics, the [webhint browser extension](https://webhint.io/docs/user-guide/extensions/extension-browser/) for performing runtime analysis of cross-browser compatibility and other checks, [GitHub bots](https://probot.github.io/) for providing more powerful GitHub functionality, [Updown](https://updown.io/) for providing app uptime monitoring, and so many more!
### Some thoughts about tooling types
There's certainly an order in which the different tooling types apply in the development lifecycle, but rest assured that you don't _have_ to have all of these in place to release a website. In fact, you don't need any of these. However, including some of these tools in your process will improve your own development experience and likely improve the overall quality of your code.
It often takes some time for new developer tools to settle down in their complexity. One of the best-known tools, Webpack, has a reputation for being overly complicated to work with, but in the latest major release, there was a huge push to simplify common usage so the configuration required is reduced down to an absolute minimum.
There's definitely no silver bullet that will guarantee success with tools, but as your experience increases you'll find workflows that work _for you_ or for your team and their projects. Once all the kinks in the process are flattened out, your toolchain should be something you can forget about and it _should_ just work.
## How to choose and get help with a particular tool
Most tools tend to get written and released in isolation, so although there's almost certainly help available it's never in the same place or format. It can therefore be hard to find help with using a tool, or even to choose what tool to use. The knowledge about which are the best tools to use is a bit tribal, meaning that if you aren't already in the web community, it is hard to find out exactly which ones to go for! This is one reason we wrote this series of articles, to hopefully provide that first step that is hard to find otherwise.
You'll probably need a combination of the following things:
- Experienced teachers, mentors, fellow students, or colleagues that have some experience, have solved such problems before, and can give advice.
- A useful specific place to search. General web searches for front-end developer tools are generally useless unless you already know the name of the tool you are searching for.
- If you are using the npm package manager to manage your dependencies for example, it is a good idea to go to the [npm homepage](https://www.npmjs.com/) and search for the type of tool you are looking for, for example try searching for "date" if you want a date formatting utility, or "formatter" if you are searching for a general code formatter. Pay attention to the popularity, quality, and maintenance scores, and how recently the package was last updated. Also click through to the tool pages to find out how many monthly downloads a package has, and whether it has good documentation that you can use to figure out whether it does what you need it to do. Based on these criteria, the [date-fns library](https://www.npmjs.com/package/date-fns) looks like a good date formatting tool to use. You'll see this tool in action and learn more about package managers in general in Chapter 3 of this module.
- If you are looking for a plugin to integrate tool functionality into your code editor, look at the code editor's plugins/extensions page β see [VSCode extensions](https://marketplace.visualstudio.com/VSCode), for example. Have a look at the featured extensions on the front page, and again, try searching for the kind of extension you want (or the tool name, for example search for "ESLint" on the VSCode extensions page). When you get results, have a look at information such as how many stars or downloads the extension has, as an indicator of its quality.
- Development-related forums to ask questions on about what tools to use, for example [MDN Learn Discourse](https://discourse.mozilla.org/c/mdn/learn/250), or [Stack Overflow](https://stackoverflow.com/).
When you've chosen a tool to use, the first port of call should be the tool project homepage. This could be a full-blown website or it might be a single readme document in a code repository. The [date-fns docs](https://date-fns.org/docs/Getting-Started) for example are pretty good, complete, and easy to follow. Some documentation however can be rather technical and academic and not a good fit for your learning needs.
Instead, you might want to find some dedicated tutorials on getting started with particular types of tools. A great starting place is to search websites like [CSS Tricks](https://css-tricks.com/), [Dev](https://dev.to/), [freeCodeCamp](https://www.freecodecamp.org/), and [Smashing Magazine](https://www.smashingmagazine.com/), as they're tailored to the web development industry.
Again, you'll probably go through several different tools as you search for the right ones for you, trying them out to see if they make sense, are well-supported, and do what you want them to do. This is fine β it is all good for learning, and the road will get smoother as you get more experience.
## Summary
That rounds off our gentle introduction to the topic of client-side web tooling, from a high level. Next up we provide you with a crash course on the command line, which is where a lot of tooling is invoked from. We'll take a look at what the command line can do and then try installing and using our first tool.
{{NextMenu("Learn/Tools_and_testing/Understanding_client-side_tools/Command_line", "Learn/Tools_and_testing/Understanding_client-side_tools")}}
| 0 |
data/mdn-content/files/en-us/learn/tools_and_testing/understanding_client-side_tools | data/mdn-content/files/en-us/learn/tools_and_testing/understanding_client-side_tools/introducing_complete_toolchain/index.md | ---
title: Introducing a complete toolchain
slug: Learn/Tools_and_testing/Understanding_client-side_tools/Introducing_complete_toolchain
page-type: learn-module-chapter
---
{{LearnSidebar}}{{PreviousMenuNext("Learn/Tools_and_testing/Understanding_client-side_tools/Package_management","Learn/Tools_and_testing/Understanding_client-side_tools/Deployment", "Learn/Tools_and_testing/Understanding_client-side_tools")}}
In the final couple of articles in the series, we will solidify your tooling knowledge by walking you through the process of building up a sample case study toolchain. We'll go all the way from setting up a sensible development environment and putting transformation tools in place to actually deploying your app on Netlify. In this article, we'll introduce the case study, set up our development environment, and set up our code transformation tools.
<table>
<tbody>
<tr>
<th scope="row">Prerequisites:</th>
<td>
Familiarity with the core <a href="/en-US/docs/Learn/HTML">HTML</a>,
<a href="/en-US/docs/Learn/CSS">CSS</a>, and
<a href="/en-US/docs/Learn/JavaScript">JavaScript</a> languages.
</td>
</tr>
<tr>
<th scope="row">Objective:</th>
<td>
To solidify what we've learnt so far by working through a complete
toolchain case study.
</td>
</tr>
</tbody>
</table>
There really are unlimited combinations of tools and ways to use them, what you see in this article and the next is only _one_ way that the featured tools can be used for a project.
> **Note:** It's also worth repeating that not all of these tools need to be run on the command line. Many of today's code editors (such as VS Code) have integration support for a _lot_ of tools via plugins.
## Introducing our case study
The toolchain that we are creating in this article will be used to build and deploy a mini-site that lists data (taken from one of [NASA's open APIs](https://api.nasa.gov/)) concerning potentially hazardous space objects that threaten our existence on Earth! It looks like this:

You can see a live version of the site at [near-misses.netlify.com](https://near-misses.netlify.app/).
## Tools used in our toolchain
In this article we're going to use the following tools and features:
- [JSX](https://react.dev/learn/writing-markup-with-jsx), a [React](https://react.dev)-related set of syntax extensions that allow you to do things like defining component structures inside JavaScript. You won't need to know React to follow this tutorial, but we've included this to give you an idea of how a non-native web language could be integrated into a toolchain.
- The latest built-in JavaScript features (at the time of writing), such as [`import`](/en-US/docs/Web/JavaScript/Reference/Statements/import).
- Useful development tools such as [Prettier](https://prettier.io/) for formatting and [ESLint](https://eslint.org/) for linting.
- [PostCSS](https://postcss.org/) to provide CSS nesting capabilities.
- [Parcel](https://parceljs.org/) to build and minify our code, and to write a bunch of configuration file content automatically for us.
- [GitHub](/en-US/docs/Learn/Tools_and_testing/GitHub) to manage our source code control.
- [Netlify](https://www.netlify.com/) to automate our deployment process.
You may not be familiar with all the above features and tools or what they are doing, but don't panic β we'll explain each part as we move through this article.
## Toolchains and their inherent complexity
As with any chain, the more links you have in your toolchain, the more complex and potentially brittle it is β for example it might be more complex to configure, and easier to break. Conversely, the fewer links, the more resilient the toolchain is likely to be.
All web projects will be different, and you need to consider what parts of your toolchain are necessary and consider each part carefully.
The smallest toolchain is one that has no links at all. You would hand code the HTML, use "vanilla JavaScript" (meaning no frameworks or intermediary languages), and manually upload it all to a server for hosting.
However, more complicated software requirements will likely benefit from the usage of tools to help simplify the development process. In addition, you should include tests before you deploy to your production server to ensure your software works as intended β this already sounds like a necessary toolchain.
For our sample project, we'll be using a toolchain specifically designed to aid our software development and support the technical choices made during the software design phase. We will however be avoiding any superfluous tooling, with the aim of keeping complexity to a minimum.
For example, we _could_ have included a tool to minimize our SVG file sizes during the build. However, this project has only 4 SVG images, which were [manually minified using SVGO](https://www.npmjs.com/package/svgo) before adding them to the project.
## A couple of prerequisites
Besides the tools we're going to install that contribute to our toolchain, we mentioned two web services in the above list of tools. Let's take this opportunity to make sure we are set up with them before we continue. You will need to create accounts with each of GitHub and Netlify if you wish to complete the tutorial.
- As mentioned previously, GitHub is a source code repository service that adds community features such as issue tracking, following project releases, and much more. In the next chapter, we will push to a GitHub code repository, which will cause a cascade effect that (should) deploy all the software to a home on the web.
- Netlify is a hosting service for static websites (that is, websites that entirely consist of files that do not change in real-time), which lets us deploy multiple times a day and freely hosts static sites of all kinds. Netlify is what provides the "home on the web" mentioned above β free hosting for us to deploy our test app to.
Once you've signed up for [GitHub](https://github.com/) (click the _Sign Up_ link on the homepage if you don't already have an account, and follow the instructions), you can use your GitHub account for authentication on [Netlify](https://www.netlify.com/) (click _Sign Up_, then choose _GitHub_ from the "Sign up with one of the following" list), so technically you only need to create one new account.
Later on, you'll need to connect your Netlify account to your GitHub repository to deploy this project; we'll see how to do that in the next chapter.
## Three stages of tools
As we talked about in [Chapter 1](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Overview), the toolchain will be structured into the following phases:
- **Safety net**: Making the software development experience stable and more efficient. We might also refer to this as our development environment.
- **Transformation**: Tooling that allows us to use the latest features of a language (e.g. JavaScript) or another language entirely (e.g. JSX or TypeScript) in our development process, and then transforms our code so that the production version still runs on a wide variety of browsers, modern and older.
- **Post development**: Tooling that comes into play after you are done with the body of development to ensure that your software makes it to the web and continues to run. In this case study we'll look at adding tests to your code, and deploying your app using Netlify so it is available for all the web to see.
Let's start working on these, beginning with our development environment.
## Creating a development environment
This part of the toolchain is sometimes seen to be delaying the actual work, and it can be very easy to fall into a "rabbit hole" of tooling where you spend a lot of time trying to get the environment "just right".
But you can look at this in the same way as setting up your physical work environment. The chair needs to be comfortable, and set up in a good position to help with your posture. You need power, Wi-Fi, and USB ports! There might be important decorations or music that help with your mental state β these are all important to do your best work possible, and they should also only need to be set up once, if done properly.
In the same way, setting up your development environment, if done well, needs to be done only once and should be reusable in many future projects. You will probably want to review this part of the toolchain semi-regularly and consider if there are any upgrades or changes you should introduce, but this shouldn't be required too often.
Your toolchain will depend on your own needs, but for this example of a (possible) complete toolchain, the tools that will be installed up front will be:
- Library installation tools β for adding dependencies.
- Code revision control.
- Code tidying tools β for tidying JavaScript, CSS, and HTML.
- Code linting tools β for linting our code.
### Library installation tools
We'll use npm to install our tools, which you first met in Chapter 2. You should have Node.js and npm installed already, but if not, [refer back to that section](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line#adding_powerups).
> **Note:** Though it's not clear from the installation process, installing npm also installs a complementary tool called npx. We will use npx later in this chapter to help run tools that are installed as local dependencies to the project.
npm will be used to install subsequent parts of our toolchain. First of all, however, we'll install git to help with revision control.
### Code revision control
It's possible you've heard of "git" before. [Git](https://git-scm.com/) is currently the most popular source code revision control tool available to developers β revision control provides many advantages, such as a way to backup your work in a remote place, and a mechanism to work in a team on the same project without fear of overwriting each other's code.
It might be obvious to some, but it bears repeating: Git is not the same thing as GitHub. Git is the revision control tool, whereas [GitHub](https://github.com/) is an online store for git repositories (plus a number of useful tools for working with them). Note that, although we're using GitHub in this chapter, there are several alternatives including [GitLab](https://about.gitlab.com/) and [Bitbucket](https://www.atlassian.com/software/bitbucket), and you could even host your own git repositories.
Using revision control in your projects and including it as part of the toolchain will help manage the evolution of your code. It offers a way to "commit" blocks of work as you progress, along with comments such as "X new feature implemented", or "Bug Z now fixed due to Y changes".
Revision control can also allow you to _branch_ out your project code, creating a separate version, and trying out new functionality on, without those changes affecting your original code.
Finally, it can help you undo changes or revert your code back to a time "when it was working" if a mistake has been introduced somewhere and you are having trouble fixing it β something all developers need to do once in a while!
Git can be [downloaded and installed via the git-scm website](https://git-scm.com/downloads) β download the relevant installer for your system, run it, and follow the on-screen prompts. This is all you need to do for now.
You can interact with git in a number of different ways, from using the command line to issue commands, to using a [git GUI app](https://git-scm.com/downloads/guis) to issue the same commands by pushing buttons, or even from directly inside your code editor, as seen in the Visual Studio Code example below:

Anyway, installing git is all we need to do for now. Let's move on.
### Code tidying tools
We'll be using Prettier, which we first met in Chapter 2, to tidy our code in this project. If you followed the directions in the [Installing Prettier](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Command_line#installing_prettier) section then you might already have Prettier installed. If not, we'll get you to install Prettier as a global utility using the terminal right now.
You can check whether you've already got it installed globally using the following command:
```bash
prettier -v
```
If installed, you'll get a version number returned like 2.0.2; if not, it'll return something along the lines of "command not found". If this is the case, install it using the following command:
```bash
npm install prettier -g
```
Now that Prettier is installed, running and tidying your code can be done on the command line on an individual file basis from anywhere on your computer, for example:
```bash
prettier --write ./src/index.html
```
> **Note:** In the command above, I use Prettier with the `--write` flag. Prettier understands this to mean "if there's any problem in my code format, go ahead and fix them, then save my file". This is fine for our development process, but we can also use `prettier` without the flag and it will only check the file. Checking the file (and not saving it) is useful for purposes like checks that run before a release - i.e. "don't release any code that's not been properly formatted."
It can be arduous to run the initial command against each file, and it would be useful to have a single command to do this for us (and the same will go for our linting tools).
There are many ways to solve this problem; here's just a few:
- Using npm scripts to run multiple commands from the command line in one go, such as `npm run tidy-code`.
- Using special "git hooks" to test if the code is formatted before a commit.
- Using code editor plugins to run Prettier commands each time a file is saved.
> **Note:** What is a git hook? Git (not GitHub) provides a system that lets us attach pre- and post- actions to the tasks we perform with git (such as committing your code). Although git hooks can be a bit overly complicated (in this author's opinion), once they're in place they can be very powerful. If you're interested in using hooks, [Husky](https://github.com/typicode/husky) is a greatly simplified route into using hooks.
For VS Code, one useful extension is the [Prettier Code Formatter by Esben Petersen](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode), which lets VSCode automatically format code upon saving. This means that any file in the project we are working on gets formatted nicely, including HTML, CSS, JavaScript, JSON, markdown, and more. All the editor needs is "Format On Save" enabled.
Like many tools made more recently Prettier comes with "sensible defaults". That means that you'll be able to use Prettier without having to configure anything (if you are happy with the [defaults](https://prettier.io/docs/en/configuration.html)). This lets you get on with what's important: the creative work.
### Code linting tools
Linting helps with code quality but also is a way to catch potential errors earlier during development. It's a key ingredient of a good toolchain and one that many development projects will include by default.
Web development linting tools mostly exist for JavaScript (though there are a few available for HTML and CSS). This makes sense: if an unknown HTML element or invalid CSS property is used, due to the resilient nature of these two languages nothing is likely to break. JavaScript is a lot more fragile β mistakenly calling a function that doesn't exist for example causes your JavaScript to break; linting JavaScript is therefore very important, especially for larger projects.
The go-to tool for JavaScript linting is [ESLint](https://eslint.org/). It's an extremely powerful and versatile tool but can be tricky to configure correctly and you could easily consume many hours trying to get a configuration _just right_!
Out of the box, ESLint is going to complain that it can't find the configuration file if you run it. The configuration file supports multiple formats but for this project, we'll use `.eslintrc.json` (the leading period means the file is hidden by default).
ESLint is installed via npm, so as per discussions in Chapter 2, you have the choice to install this tool locally or globally. Using both is recommended:
- For projects you intend to share, you should always include ESLint as a local dependency so that anyone making their own copy can follow the rules you've applied to the project.
- You should also consider having ESLint installed globally so that you can quickly use it to check any file you want.
For the sake of simplicity, in this chapter, we're not going to explore all the features of ESLint, but we will put a configuration in place that works for our particular project and its requirements. However, bear in mind that if you want to refine and enforce a rule about how your code looks (or validates), it's very likely that it can be done with the right ESLint configuration.
A little later in this chapter, we'll provide the ESLint config. Once a working configuration is in place, running the command can generate some useful information. Here is an example ESLint output:
```bash
./my-project/src/index.js
2:8 error 'React' is defined but never used no-unused-vars
22:20 error 'body' is defined but never used no-unused-vars
96:19 error 'b' is defined but never used no-unused-vars
β 3 problems (3 errors, 0 warnings)
```
> **Note:** We'll install ESLint in the next section; don't worry about this for now.
As with other tools, code editor integration support is typically good for ESLint, and potentially more useful as it can give us real-time feedback when issues crop up:

## Configuring the initial project
Using these tools, a new project can be set up safely in the knowledge that many "basic" issues will be caught early on.
Using the command line, we can create the project, install the initial tooling, and create rudimentary configuration files. Again, once you've repeated this process a few times, you'll get a feel for what your default setup should be. Of course, this is _just one_ possible configuration.
### Initial setup
OK, let's get the initial project setup out of the way.
1. Start off by opening your terminal, and navigating to a place that you'll be able to find and get to easily. The Desktop perhaps, or your home or documents folder?
2. Next, run the following commands to create a folder to keep your project in, and go inside the folder:
```bash
mkdir will-it-miss
cd will-it-miss
```
3. Now we will create a new directory for all of our website's development code to live in. Run the following now:
```bash
mkdir src
```
Code organization tends to be quite subjective from team to team. For this project, the source code will live in `src`.
4. Making sure you are inside the root of the `will-it-miss` directory, enter the following command to start git's source control functionality working on the directory:
```bash
git init
```
This means that you'll now be able to start storing revisions to the folder's contents, saving it to a remote repository, etc. More on this later!
5. Next, enter the following command to turn your directory into an npm package, with the advantages that we discussed in the previous article:
```bash
npm init --force
```
This will create a default `package.json` file that we can configure later on if desired. The `--force` flag causes the command to instantly create a default `package.json` file without asking you all the usual questions about what contents you want it to have (as we saw previously). We only need the defaults for now, so this saves us a bit of time.
#### Getting the project code files
At this point, we'll get hold of the project's code files (HTML, CSS, JavaScript, etc.), and put them in our `src` directory. We won't teach you how they work, as that is not the point of this chapter. They are merely here to run the tools on, to teach you about how _they_ work.
1. To get hold of the code files, visit <https://github.com/remy/mdn-will-it-miss> and download and unzip the contents of this repo onto your local drive somewhere. You can download the entire project as a zip file by selecting _Clone or download_ > _Download ZIP_.

2. Now copy the contents of the project's `src` directory to your currently empty `src` directory.
We have our project files in place. That's all we need to do for now!
> **Note:** To set up the project on your local machine, go to the root directory of the unzipped folder, open a terminal in that location, and execute the `npm install` command in the terminal. This will install all project dependencies that are mentioned in the `package.json` file.
#### Installing our tools
Now it's time to install the initial set of tools we'll be using in our dev environment. Run the following from inside your project's root directory:
```bash
npm install --save-dev eslint prettier babel-eslint
```
There are two important things to note about the command you just ran. The first is that we're installing the dependencies locally to the project β installing tools locally is better for a specific project. Installing locally (not including the `--global` option) allows us to easily recreate this setup on other machines.
The second important part of this install command is the `--save-dev` option. This tells the npm tool that these particular dependencies are only needed for development (npm therefore lists them in the `package.json` file under `devDependencies`, not `dependencies`). This means that if this project is installed in production mode these dependencies will not be installed. A "typical" project can have many development dependencies which are not needed to actually run the code in production. Keeping them as separate dependencies reduces any unnecessary work when deploying to production (which we will look at in the next chapter).
Before starting on the development of the actual application code, a little configuration is required for our tools to work properly. It's not a prerequisite of developing for the web, but it's useful to have the tools configured correctly if they're going to help catch errors during development β which ESLint is particularly useful for.
### Configuring our tools
In the root of the project (not in the `src` directory), we will add configuration files to configure some of our tools, namely Prettier and ESLint. This is general practice for tool configuration β you tend to find the config files in the project root, which more often than not contain configuration options expressed in a JSON structure (though our tools and many others also support YAML, which you can switch to if that's your preferred flavor of the configuration file).
1. First of all, create a file in the root of your `will-it-miss` directory called `.prettierrc.json`.
2. To configure Prettier, give `.prettierrc.json` the following contents:
```json
{
"singleQuote": true,
"trailingComma": "es5"
}
```
With these settings, when Prettier formats JavaScript for you it will use single quotes for all your quoted values, and it won't use trailing commas (a newer feature of ECMAScript that will cause errors in older browsers). You can find more about [configuring Prettier](https://prettier.io/docs/en/configuration.html) in its documentation.
3. Next up, we'll configure ESLint β create another file in the root of your `will-it-miss` directory called `.eslintrc.json`, and give it the following contents:
```json
{
"env": {
"es6": true,
"browser": true
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module"
},
"rules": {
"no-console": 0
}
}
```
The above ESLint configuration says that we want to use the "recommended" ESLint settings, that we're going to allow usage of ES6 features (such as [`map()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) or [`Set()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/Set)), that we can use module [`import`](/en-US/docs/Web/JavaScript/Reference/Statements/import) statements, and that using [`console.log()`](/en-US/docs/Web/API/console/log_static) is allowed.
4. However, in the project's source files we are using React JSX syntax (for your real projects you might use React or Vue or any other framework, or no framework at all!).
Putting JSX syntax in the middle of our JavaScript is going to cause ESLint to complain pretty quickly with the current configuration, so we'll need to add a little more configuration to the ESLint settings to get it to accept JSX features.
The final config file should look like this β add in the bolded parts and save it:
```json
{
"env": {
"es6": true,
"browser": true
},
"extends": ["eslint:recommended", "plugin:react/recommended"],
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true
}
},
"plugins": ["react"],
"rules": {
"semi": "error",
"no-console": 0,
"react/jsx-uses-vars": "error"
}
}
```
As the configuration now uses a plugin called "React", this development dependency also needs to be installed, so that the code is there to actually run that part of the linting process.
5. Run the following terminal command in the root of your project folder:
```bash
npm install --save-dev eslint-plugin-react
```
There's a complete [list of ESLint rules](https://eslint.org/docs/rules/) that you can tweak and configure to your heart's content and many companies and teams have published their [own ESLint configurations](https://www.npmjs.com/search?q=keywords:eslintconfig), which can sometimes be useful either to get inspiration or to select one that you feel suits your own standards. A forewarning though: ESLint configuration is a very deep rabbit hole!
That's our dev environment setup complete at this point. Now, finally we're (very nearly) ready to code.
## Build and transformation tools
For this project, as mentioned above, React is going to be used, which also means that JSX will be used in the source code. The project will also use the latest JavaScript features.
An immediate issue is that no browser has native support for JSX; it is an intermediate language that is meant to be compiled into languages the browser understands in the production code.
If the browser tries to run the source JavaScript it will immediately complain; the project needs a build tool to transform the source code to something the browser can consume without issue.
There's a number of choices for transform tools and though WebPack is a particularly popular one, this project is going to use Parcel β specifically because it requires a lot less configuration.
Parcel works on the basis that it will try to configure your development requirements on the fly. Parcel will watch the code and run a live-reloading web server during development. This also means that Parcel will install our software dependencies automatically as they are referenced in the source code, as we [saw in Chapter 3](/en-US/docs/Learn/Tools_and_testing/Understanding_client-side_tools/Package_management#using_the_package_ecosystem).
Parcel will take care of installing any transformation tooling and configuration required without us needing to intervene (in most cases).
Then as a final bonus, Parcel can bundle and prepare the code for production deployment, taking care of minification and browser compatibility requirements.
We therefore need to install the parcel dependency in our project too β run the following command in your terminal:
```bash
npm install --save-dev parcel-bundler
```
### Using future features
The code for our project is using some new web features including features that are so new they aren't fully standardized yet. For example, instead of reaching for a tool like [Sass](https://sass-lang.com/), this particular project uses the W3C proposal for [CSS nesting](https://drafts.csswg.org/css-nesting/). CSS nesting allows us to nest CSS selectors and properties inside one another thus creating more specific selector scope. Sass was one of the first preprocessors to support nesting (if not the first) but now after many years, nesting looks like it will soon be standardized, which means that we will have it available in our browsers without needing build tools.
Until then, Parcel will do the transformation between nested CSS and natively supported CSS with the help of [PostCSS](https://postcss.org/), which Parcel works with out of the box. Since we've specifically decided this project should use CSS nesting (instead of Sass), the project will need to include a PostCSS plugin.
Let's use the [postcss-preset-env](https://preset-env.cssdb.org/), which lets us "use tomorrow's CSS today". To do so, follow these steps:
1. Add a single file called `.postcssrc` to the root of your project directory.
2. Add the following contents to the new file, which will automagically give us full access to the latest CSS features:
```json
{
"plugins": {
"postcss-preset-env": {
"stage": 0
}
}
}
```
That's all we need to do β remember that Parcel installs the dependencies for us by default!
Although this stage of our toolchain can be quite painful, because we've chosen a tool that purposely tries to reduce configuration and complexity, there's really nothing more we need to do during the development phase. Modules are correctly imported, nested CSS is correctly transformed to "regular CSS", and our development is unimpeded by the build process.
Now our software is ready to be written!
## Running the transformation
To start working with our project, we'll run the Parcel server on the command line. In its default mode it will watch for changes in your code and automatically install your dependencies. This is nice because we don't have to flit back and forth between the code and the command line.
1. To start Parcel off in the background, go to your terminal and run the following command:
```bash
npx parcel src/index.html
```
You should see an output like this (once the dependencies have been installed):
```bash
Server running at http://localhost:1234
β¨ Built in 129ms.
```
Parcel also installs the dependencies that we will use in our code, including react, react-dom, react-async-hook, date-fns, and format-number. This first run will therefore be longer than a typical run of Parcel.
> **Note:** if you run Parcel on this project and are faced with an error that reads `Error: ENOENT: no such file or directory`, stop the process using <kbd>Ctrl</kbd> + <kbd>C</kbd> and then try re-running it.
The server is now running on the URL that was printed (in this case localhost:1234).
2. Go to this URL in your browser and you will see the example app running!
Another clever trick Parcel has up its sleeve is that any changes to your source code will now trigger an update in the browser. To try this out:
1. Load up the file `src/components/App.js` in your favorite text editor.
2. Search for the text "near misses", and replace it with something silly like "flying pigs".
3. Save the file, then go straight back to the app running in your browser. You'll notice that the browser has automatically refreshed, and the line "\<date> there will be \<number> near misses" at the top of the page has been changed!
You could also try using ESLint and Prettier too β try deliberately removing a load of the whitespace from one of your files and running Prettier on it to clean it up, or introduce a syntax error into one of your JavaScript files and see what errors ESLint gives you when you try to use Parcel to build it again.
## Summary
We've come a long way in this chapter, building up a rather nice local development environment to create an application in.
At this point during web software development you would usually be crafting your code for the software you intend to build. Since this module is all about learning the tools around web development, not web development code itself, we won't be teaching you any actual coding β you'll find that information in the rest of MDN!
Instead, we've written an example project for you to use your tools on. We'd suggest that you work through the rest of the chapter using our example code, and then you can try changing the contents of the src directory to your own project and publishing that on Netlify instead! And indeed, deploying to Netlify will be the end goal of the next chapter!
{{PreviousMenuNext("Learn/Tools_and_testing/Understanding_client-side_tools/Package_management","Learn/Tools_and_testing/Understanding_client-side_tools/Deployment", "Learn/Tools_and_testing/Understanding_client-side_tools")}}
| 0 |
data/mdn-content/files/en-us | data/mdn-content/files/en-us/webassembly/index.md | ---
title: WebAssembly
slug: WebAssembly
page-type: landing-page
spec-urls: https://webassembly.github.io/spec/js-api/
---
{{WebAssemblySidebar}}
WebAssembly is a type of code that can be run in modern web browsers β it is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages such as C/C++, C# and Rust with a compilation target so that they can run on the web. It is also designed to run alongside JavaScript, allowing both to work together.
## In a Nutshell
WebAssembly has huge implications for the web platform β it provides a way to run code written in multiple languages on the web at near-native speed, with client apps running on the web that previously couldn't have done so.
WebAssembly is designed to complement and run alongside JavaScript β using the WebAssembly JavaScript APIs, you can load WebAssembly modules into a JavaScript app and share functionality between the two. This allows you to take advantage of WebAssembly's performance and power and JavaScript's expressiveness and flexibility in the same app, even if you don't know how to write WebAssembly code.
And what's even better is that it is being developed as a web standard via the [W3C WebAssembly Working Group](https://www.w3.org/wasm/) and [Community Group](https://www.w3.org/community/webassembly/) with active participation from all major browser vendors.
## Guides
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- : Get started by reading the high-level concepts behind WebAssembly β what it is, why it is so useful, how it fits into the web platform (and beyond), and how to use it.
- [Compiling a New C/C++ Module to WebAssembly](/en-US/docs/WebAssembly/C_to_Wasm)
- : When you've written code in C/C++, you can then compile it into Wasm using a tool like [Emscripten](https://emscripten.org/). Let's look at how it works.
- [Compiling an Existing C Module to WebAssembly](/en-US/docs/WebAssembly/existing_C_to_Wasm)
- : A core use-case for WebAssembly is to take the existing ecosystem of C libraries and allow developers to use them on the web.
- [Compiling from Rust to WebAssembly](/en-US/docs/WebAssembly/Rust_to_Wasm)
- : If you've written some Rust code, you can compile it into WebAssembly! This tutorial takes you through all you need to know to compile a Rust project to Wasm and use it in an existing web app.
- [Loading and running WebAssembly code](/en-US/docs/WebAssembly/Loading_and_running)
- : After you have a Wasm module, this article covers how to fetch, compile and instantiate it, combining the [WebAssembly JavaScript](/en-US/docs/WebAssembly/JavaScript_interface) API with the [Fetch](/en-US/docs/Web/API/Fetch_API) or [XHR](/en-US/docs/Web/API/XMLHttpRequest) APIs.
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
- : Once you've loaded a Wasm module, you'll want to use it. In this article, we show you how to use WebAssembly via the WebAssembly JavaScript API.
- [Exported WebAssembly functions](/en-US/docs/WebAssembly/Exported_functions)
- : Exported WebAssembly functions are the JavaScript reflections of WebAssembly functions, which allow calling WebAssembly code from JavaScript. This article describes what they are.
- [Understanding WebAssembly text format](/en-US/docs/WebAssembly/Understanding_the_text_format)
- : This article explains the Wasm text format. This is the low-level textual representation of a Wasm module shown in browser developer tools when debugging.
- [Converting WebAssembly text format to Wasm](/en-US/docs/WebAssembly/Text_format_to_Wasm)
- : This article provides a guide on how to convert a WebAssembly module written in text format into a Wasm binary.
## API reference
- [WebAssembly instruction reference](/en-US/docs/WebAssembly/Reference)
- : Reference documentation with interactive samples for the set of WebAssembly operators.
- [WebAssembly JavaScript interface](/en-US/docs/WebAssembly/JavaScript_interface)
- : This object acts as the namespace for all WebAssembly-related functionality.
- [`WebAssembly.Global()`](/en-US/docs/WebAssembly/JavaScript_interface/Global)
- : A `WebAssembly.Global` object represents a global variable instance, accessible from both JavaScript and importable/exportable across one or more [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) instances. This allows dynamic linking of multiple modules.
- [`WebAssembly.Module()`](/en-US/docs/WebAssembly/JavaScript_interface/Module)
- : A `WebAssembly.Module` object contains stateless WebAssembly code that has already been compiled by the browser and can be efficiently [shared with Workers](/en-US/docs/Web/API/Worker/postMessage), and instantiated multiple times.
- [`WebAssembly.Instance()`](/en-US/docs/WebAssembly/JavaScript_interface/Instance)
- : A `WebAssembly.Instance` object is a stateful, executable instance of a `Module`. `Instance` objects contain all the [Exported WebAssembly functions](/en-US/docs/WebAssembly/Exported_functions) that allow calling into WebAssembly code from JavaScript.
- [`WebAssembly.compile()`](/en-US/docs/WebAssembly/JavaScript_interface/compile_static)
- : The `WebAssembly.compile()` function compiles WebAssembly binary code into a `WebAssembly.Module` object.
- [`WebAssembly.compileStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/compileStreaming_static)
- : The `WebAssembly.compileStreaming()` function compiles a `WebAssembly.Module` directly from a streamed underlying source.
- [`WebAssembly.instantiate()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static)
- : The `WebAssembly.instantiate()` function allows you to compile and instantiate WebAssembly code.
- [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static)
- : The `WebAssembly.instantiateStreaming()` function is the primary API for compiling and instantiating WebAssembly code, returning both a `Module` and its first `Instance`.
- [`WebAssembly.validate()`](/en-US/docs/WebAssembly/JavaScript_interface/validate_static)
- : The `WebAssembly.validate()` function validates a given typed array of WebAssembly binary code.
- [`WebAssembly.Memory()`](/en-US/docs/WebAssembly/JavaScript_interface/Memory)
- : A `WebAssembly.Memory` object is a resizable {{jsxref("Global_objects/ArrayBuffer", "ArrayBuffer")}} that holds the raw bytes of memory accessed by an `Instance`.
- [`WebAssembly.Table()`](/en-US/docs/WebAssembly/JavaScript_interface/Table)
- : A `WebAssembly.Table` object is a resizable typed array of opaque values, like function references, that are accessed by an `Instance`.
- [`WebAssembly.Tag()`](/en-US/docs/WebAssembly/JavaScript_interface/Tag)
- : The `WebAssembly.Tag` object defines a type of WebAssembly exception that can be thrown to/from WebAssembly code.
- [`WebAssembly.Exception()`](/en-US/docs/WebAssembly/JavaScript_interface/Exception)
- : The `WebAssembly.Exception` object represents a runtime exception thrown from WebAssembly to JavaScript, or thrown from JavaScript to a WebAssembly exception handler.
- [`WebAssembly.CompileError()`](/en-US/docs/WebAssembly/JavaScript_interface/CompileError)
- : Creates a new WebAssembly `CompileError` object.
- [`WebAssembly.LinkError()`](/en-US/docs/WebAssembly/JavaScript_interface/LinkError)
- : Creates a new WebAssembly `LinkError` object.
- [`WebAssembly.RuntimeError()`](/en-US/docs/WebAssembly/JavaScript_interface/RuntimeError)
- : Creates a new WebAssembly `RuntimeError` object.
## Examples
- [WASMSobel](https://github.com/JasonWeathersby/WASMSobel)
- See our [webassembly-examples](https://github.com/mdn/webassembly-examples/) repo for a number of other examples.
## Specifications
{{Specifications}}
## See also
- [WebAssembly on Mozilla Research](https://research.mozilla.org/)
- [webassembly.org](https://webassembly.org/)
- [WebAssembly articles on Mozilla Hacks blog](https://hacks.mozilla.org/category/webassembly/)
- [W3C WebAssembly Community Group](https://www.w3.org/community/webassembly/)
- [Emscripting a C Library to Wasm](https://web.dev/articles/emscripting-a-c-library)
| 0 |
data/mdn-content/files/en-us/webassembly | data/mdn-content/files/en-us/webassembly/loading_and_running/index.md | ---
title: Loading and running WebAssembly code
slug: WebAssembly/Loading_and_running
page-type: guide
---
{{WebAssemblySidebar}}
To use WebAssembly in JavaScript, you first need to pull your module into memory before compilation/instantiation. This article provides a reference for the different mechanisms that can be used to fetch WebAssembly bytecode, as well as how to compile/instantiate then run it.
## What are the options?
WebAssembly is not yet integrated with `<script type='module'>` or `import` statements, thus there is not a path to have the browser fetch modules for you using imports.
The older [`WebAssembly.compile`](/en-US/docs/WebAssembly/JavaScript_interface/compile_static)/[`WebAssembly.instantiate`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static) methods require you to create an {{jsxref("ArrayBuffer")}} containing your WebAssembly module binary after fetching the raw bytes, and then compile/instantiate it. This is analogous to `new Function(string)`, except that we are substituting a string of characters (JavaScript source code) with an array buffer of bytes (WebAssembly source code).
The newer [`WebAssembly.compileStreaming`](/en-US/docs/WebAssembly/JavaScript_interface/compileStreaming_static)/[`WebAssembly.instantiateStreaming`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) methods are a lot more efficient β they perform their actions directly on the raw stream of bytes coming from the network, cutting out the need for the {{jsxref("ArrayBuffer")}} step.
So how do we get those bytes into an array buffer and compiled? The following sections explain.
## Using Fetch
[Fetch](/en-US/docs/Web/API/Fetch_API) is a convenient, modern API for fetching network resources.
The quickest, most efficient way to fetch a Wasm module is using the newer [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) method, which can take a `fetch()` call as its first argument, and will handle fetching, compiling, and instantiating the module in one step, accessing the raw byte code as it streams from the server:
```js
WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
(results) => {
// Do something with the results!
},
);
```
If we used the older [`WebAssembly.instantiate()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static) method, which doesn't work on the direct stream, we'd need an extra step of converting the fetched byte code to an {{jsxref("ArrayBuffer")}}, like so:
```js
fetch("module.wasm")
.then((response) => response.arrayBuffer())
.then((bytes) => WebAssembly.instantiate(bytes, importObject))
.then((results) => {
// Do something with the results!
});
```
### Aside on instantiate() overloads
The [`WebAssembly.instantiate()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static) function has two overload forms β the one shown above takes the byte code to compile as an argument and returns a Promise that resolves to an object containing both the compiled module object and an instantiated instance of it. The object looks like this:
```js-nolint
{
module: Module, // The newly compiled WebAssembly.Module object,
instance: Instance, // A new WebAssembly.Instance of the module object
}
```
> **Note:** Usually we only care about the instance, but it's useful to have the module in case we want to cache it, share it with another worker or window via [`postMessage()`](/en-US/docs/Web/API/MessagePort/postMessage), or create more instances.
> **Note:** The second overload form takes a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object as an argument, and returns a promise directly containing the instance object as the result. See the [Second overload example](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static#second_overload_example).
### Running your WebAssembly code
Once you've got your WebAssembly instance available in your JavaScript, you can then start using features of it that have been exported via the [`WebAssembly.Instance.exports`](/en-US/docs/WebAssembly/JavaScript_interface/Instance/exports) property. Your code might look something like this:
```js
WebAssembly.instantiateStreaming(fetch("myModule.wasm"), importObject).then(
(obj) => {
// Call an exported function:
obj.instance.exports.exported_func();
// or access the buffer contents of an exported memory:
const i32 = new Uint32Array(obj.instance.exports.memory.buffer);
// or access the elements of an exported table:
const table = obj.instance.exports.table;
console.log(table.get(0)());
},
);
```
> **Note:** For more information on how exporting from a WebAssembly module works, have a read of [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API), and [Understanding WebAssembly text format](/en-US/docs/WebAssembly/Understanding_the_text_format).
## Using XMLHttpRequest
[`XMLHttpRequest`](/en-US/docs/Web/API/XMLHttpRequest) is somewhat older than Fetch, but can still be happily used to get a typed array. Again, assuming our module is called `simple.wasm`:
1. Create a new {{domxref("XMLHttpRequest()")}} instance, and use its {{domxref("XMLHttpRequest.open","open()")}} method to open a request, setting the request method to `GET`, and declaring the path to the file we want to fetch.
2. The key part of this is to set the response type to `'arraybuffer'` using the {{domxref("XMLHttpRequest.responseType","responseType")}} property.
3. Next, send the request using {{domxref("XMLHttpRequest.send()")}}.
4. We then use the {{domxref("XMLHttpRequest.load_event", "load")}} event handler to invoke a function when the response has finished downloading β in this function we get the array buffer from the {{domxref("XMLHttpRequest.response", "response")}} property, and then feed that into our [`WebAssembly.instantiate()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static) method as we did with Fetch.
The final code looks like this:
```js
const request = new XMLHttpRequest();
request.open("GET", "simple.wasm");
request.responseType = "arraybuffer";
request.send();
request.onload = () => {
const bytes = request.response;
WebAssembly.instantiate(bytes, importObject).then((results) => {
results.instance.exports.exported_func();
});
};
```
> **Note:** You can see an example of this in action in [xhr-wasm.html](https://mdn.github.io/webassembly-examples/js-api-examples/xhr-wasm.html).
| 0 |
data/mdn-content/files/en-us/webassembly | data/mdn-content/files/en-us/webassembly/understanding_the_text_format/index.md | ---
title: Understanding WebAssembly text format
slug: WebAssembly/Understanding_the_text_format
page-type: guide
---
{{WebAssemblySidebar}}
To enable WebAssembly to be read and edited by humans, there is a textual representation of the Wasm binary format. This is an intermediate form designed to be exposed in text editors, browser developer tools, etc. This article explains how that text format works, in terms of the raw syntax, and how it is related to the underlying bytecode it represents β and the wrapper objects representing Wasm in JavaScript.
> **Note:** This is potentially overkill if you are a web developer who just wants to load a Wasm module into a page and use it in your code (see [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)), but it is more useful if for example, you want to write Wasm modules to optimize the performance of your JavaScript library, or build your own WebAssembly compiler.
## S-expressions
In both the binary and textual formats, the fundamental unit of code in WebAssembly is a module. In the text format, a module is represented as one big S-expression. S-expressions are a very old and very simple textual format for representing trees, and thus we can think of a module as a tree of nodes that describe the module's structure and its code. Unlike the Abstract Syntax Tree of a programming language, though, WebAssembly's tree is pretty flat, mostly consisting of lists of instructions.
First, let's see what an S-expression looks like. Each node in the tree goes inside a pair of parentheses β `( ... )`. The first label inside the parenthesis tells you what type of node it is, and after that there is a space-separated list of either attributes or child nodes. So that means the WebAssembly S-expression:
```wasm
(module (memory 1) (func))
```
represents a tree with the root node "module" and two child nodes, a "memory" node with the attribute "1" and a "func" node. We'll see shortly what these nodes actually mean.
### The simplest module
Let's start with the simplest, shortest possible Wasm module.
```wasm
(module)
```
This module is totally empty, but is still a valid module.
If we convert our module to binary now (see [Converting WebAssembly text format to Wasm](/en-US/docs/WebAssembly/Text_format_to_Wasm)), we'll see just the 8 byte module header described in the [binary format](https://webassembly.github.io/spec/core/binary/modules.html#binary-module):
```wasm
0000000: 0061 736d ; WASM_BINARY_MAGIC
0000004: 0100 0000 ; WASM_BINARY_VERSION
```
### Adding functionality to your module
Ok, that's not very interesting, let's add some executable code to this module.
All code in a webassembly module is grouped into functions, which have the following pseudocode structure:
```wasm
( func <signature> <locals> <body> )
```
- The **signature** declares what the function takes (parameters) and returns (return values).
- The **locals** are like vars in JavaScript, but with explicit types declared.
- The **body** is just a linear list of low-level instructions.
So this is similar to functions in other languages, even if it looks different because it is an S-expression.
## Signatures and parameters
The signature is a sequence of parameter type declarations followed by a list of return type declarations. It is worth noting here that:
- The absence of a `(result)` means the function doesn't return anything.
- In the current iteration, there can be at most 1 return type, but [later this will be relaxed](https://github.com/WebAssembly/spec/blob/master/proposals/multi-value/Overview.md) to any number.
Each parameter has a type explicitly declared; Wasm [Number types](#number_types), [Reference types](#reference_types), [Vector types](#vector_types).
The number types are:
- `i32`: 32-bit integer
- `i64`: 64-bit integer
- `f32`: 32-bit float
- `f64`: 64-bit float
A single parameter is written `(param i32)` and the return type is written `(result i32)`, hence a binary function that takes two 32-bit integers and returns a 64-bit float would be written like this:
```wasm
(func (param i32) (param i32) (result f64) ...)
```
After the signature, locals are listed with their type, for example `(local i32)`. Parameters are basically just locals that are initialized with the value of the corresponding argument passed by the caller.
## Getting and setting locals and parameters
Locals/parameters can be read and written by the body of the function with the `local.get` and `local.set` instructions.
The `local.get`/`local.set` commands refer to the item to be got/set by its numeric index: parameters are referred to first, in order of their declaration, followed by locals in order of their declaration. So given the following function:
```wasm
(func (param i32) (param f32) (local f64)
local.get 0
local.get 1
local.get 2)
```
The instruction `local.get 0` would get the i32 parameter, `local.get 1` would get the f32 parameter, and `local.get 2` would get the f64 local.
There is another issue here β using numeric indices to refer to items can be confusing and annoying, so the text format allows you to name parameters, locals, and most other items by including a name prefixed by a dollar symbol (`$`) just before the type declaration.
Thus, you could rewrite our previous signature like so:
```wasm
(func (param $p1 i32) (param $p2 f32) (local $loc f64) β¦)
```
And then could write `local.get $p1` instead of `local.get 0`, etc. (Note that when this text gets converted to binary, though, the binary will contain only the integer.)
## Stack machines
Before we can write a function body, we have to talk about one more thing: **stack machines**. Although the browser compiles it to something more efficient, Wasm execution is defined in terms of a stack machine where the basic idea is that every type of instruction pushes and/or pops a certain number of `i32`/`i64`/`f32`/`f64` values to/from a stack.
For example, `local.get` is defined to push the value of the local it read onto the stack, and `i32.add` pops two `i32` values (it implicitly grabs the previous two values pushed onto the stack), computes their sum (modulo 2^32) and pushes the resulting i32 value.
When a function is called, it starts with an empty stack which is gradually filled up and emptied as the body's instructions are executed. So for example, after executing the following function:
```wasm
(func (param $p i32)
(result i32)
local.get $p
local.get $p
i32.add)
```
The stack contains exactly one `i32` value β the result of the expression (`$p + $p`), which is handled by `i32.add`. The return value of a function is just the final value left on the stack.
The WebAssembly validation rules ensure the stack matches exactly: if you declare a `(result f32)`, then the stack must contain exactly one `f32` at the end. If there is no result type, the stack must be empty.
## Our first function body
As mentioned before, the function body is a list of instructions that are followed as the function is called. Putting this together with what we have already learned, we can finally define a module containing our own simple function:
```wasm
(module
(func (param $lhs i32) (param $rhs i32) (result i32)
local.get $lhs
local.get $rhs
i32.add))
```
This function gets two parameters, adds them together, and returns the result.
There are a lot more things that can be put inside function bodies, but we will start off simple for now, and you'll see a lot more examples as you go along. For a full list of the available opcodes, consult the [webassembly.org Semantics reference](https://webassembly.github.io/spec/core/exec/index.html).
### Calling the function
Our function won't do very much on its own β now we need to call it. How do we do that? Like in an ES module, Wasm functions must be explicitly exported by an `export` statement inside the module.
Like locals, functions are identified by an index by default, but for convenience, they can be named. Let's start by doing this β first, we'll add a name preceded by a dollar sign, just after the `func` keyword:
```wasm
(func $add β¦)
```
Now we need to add an export declaration β this looks like so:
```wasm
(export "add" (func $add))
```
Here, `add` is the name the function will be identified by in JavaScript whereas `$add` picks out which WebAssembly function inside the Module is being exported.
So our final module (for now) looks like this:
```wasm
(module
(func $add (param $lhs i32) (param $rhs i32) (result i32)
local.get $lhs
local.get $rhs
i32.add)
(export "add" (func $add))
)
```
If you want to follow along with the example, save the above our module into a file called `add.wat`, then convert it into a binary file called `add.wasm` using wabt (see [Converting WebAssembly text format to Wasm](/en-US/docs/WebAssembly/Text_format_to_Wasm) for details).
Next, we'll asynchronously instantiate our binary (see [Loading and running WebAssembly code](/en-US/docs/WebAssembly/Loading_and_running)) and execute our `add` function in JavaScript (we can now find `add()` in the [`exports`](/en-US/docs/WebAssembly/JavaScript_interface/Instance/exports) property of the instance):
```js
WebAssembly.instantiateStreaming(fetch("add.wasm")).then((obj) => {
console.log(obj.instance.exports.add(1, 2)); // "3"
});
```
> **Note:** You can find this example in GitHub as [add.html](https://github.com/mdn/webassembly-examples/blob/main/understanding-text-format/add.html) ([see it live also](https://mdn.github.io/webassembly-examples/understanding-text-format/add.html)). Also see [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) for more details about the instantiate function.
## Exploring fundamentals
Now we've covered the real basics, let's move on to look at some more advanced features.
### Calling functions from other functions in the same module
The `call` instruction calls a single function, given its index or name. For example, the following module contains two functions β one just returns the value 42, the other returns the result of calling the first plus one:
```wasm
(module
(func $getAnswer (result i32)
i32.const 42)
(func (export "getAnswerPlus1") (result i32)
call $getAnswer
i32.const 1
i32.add))
```
> **Note:** `i32.const` just defines a 32-bit integer and pushes it onto the stack. You could swap out the `i32` for any of the other available types, and change the value of the const to whatever you like (here we've set the value to `42`).
In this example you'll notice an `(export "getAnswerPlus1")` section, declared just after the `func` statement in the second function β this is a shorthand way of declaring that we want to export this function, and defining the name we want to export it as.
This is functionally equivalent to including a separate function statement outside the function, elsewhere in the module in the same manner as we did before, e.g.:
```wasm
(export "getAnswerPlus1" (func $functionName))
```
The JavaScript code to call our above module looks like so:
```js
WebAssembly.instantiateStreaming(fetch("call.wasm")).then((obj) => {
console.log(obj.instance.exports.getAnswerPlus1()); // "43"
});
```
### Importing functions from JavaScript
We have already seen JavaScript calling WebAssembly functions, but what about WebAssembly calling JavaScript functions? WebAssembly doesn't actually have any built-in knowledge of JavaScript, but it does have a general way to import functions that can accept either JavaScript or Wasm functions. Let's look at an example:
```wasm
(module
(import "console" "log" (func $log (param i32)))
(func (export "logIt")
i32.const 13
call $log))
```
WebAssembly has a two-level namespace so the import statement here is saying that we're asking to import the `log` function from the `console` module. You can also see that the exported `logIt` function calls the imported function using the `call` instruction we introduced above.
Imported functions are just like normal functions: they have a signature that WebAssembly validation checks statically, and they are given an index and can be named and called.
JavaScript functions have no notion of signature, so any JavaScript function can be passed, regardless of the import's declared signature. Once a module declares an import, the caller of [`WebAssembly.instantiate()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static) must pass in an import object that has the corresponding properties.
For the above, we need an object (let's call it `importObject`) such that `importObject.console.log` is a JavaScript function.
This would look like the following:
```js
const importObject = {
console: {
log(arg) {
console.log(arg);
},
},
};
WebAssembly.instantiateStreaming(fetch("logger.wasm"), importObject).then(
(obj) => {
obj.instance.exports.logIt();
},
);
```
> **Note:** You can find this example on GitHub as [logger.html](https://github.com/mdn/webassembly-examples/blob/main/understanding-text-format/logger.html) ([see it live also](https://mdn.github.io/webassembly-examples/understanding-text-format/logger.html)).
### Declaring globals in WebAssembly
WebAssembly has the ability to create global variable instances, accessible from both JavaScript and importable/exportable across one or more [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) instances. This is very useful, as it allows dynamic linking of multiple modules.
In WebAssembly text format, it looks something like this (see [global.wat](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/global.wat) in our GitHub repo; also see [global.html](https://mdn.github.io/webassembly-examples/js-api-examples/global.html) for a live JavaScript example):
```wasm
(module
(global $g (import "js" "global") (mut i32))
(func (export "getGlobal") (result i32)
(global.get $g))
(func (export "incGlobal")
(global.set $g
(i32.add (global.get $g) (i32.const 1))))
)
```
This looks similar to what we've seen before, except that we specify a global value using the keyword `global`, and we also specify the keyword `mut` along with the value's datatype if we want it to be mutable.
To create an equivalent value using JavaScript, you'd use the [`WebAssembly.Global()`](/en-US/docs/WebAssembly/JavaScript_interface/Global) constructor:
```js
const global = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
```
### WebAssembly Memory
The above example is a pretty terrible logging function: it only prints a single integer! What if we wanted to log a text string? To deal with strings and other more complex data types, WebAssembly provides **memory** (although we also have [Reference types](#reference_types) in newer implementation of WebAssembly). According to WebAssembly, memory is just a large array of bytes that can grow over time. WebAssembly contains instructions like `i32.load` and `i32.store` for reading and writing from [linear memory](https://webassembly.github.io/spec/core/exec/index.html#linear-memory).
From JavaScript's point of view, it's as though memory is all inside one big (resizable) {{jsxref("ArrayBuffer")}}. That's literally all that asm.js has to play with (except that it isn't resizable; see the asm.js [Programming model](http://asmjs.org/spec/latest/#programming-model)).
So a string is just a sequence of bytes somewhere inside this linear memory. Let's assume that we've written a suitable string of bytes to memory; how do we pass that string out to JavaScript?
The key is that JavaScript can create WebAssembly linear memory instances via the [`WebAssembly.Memory()`](/en-US/docs/WebAssembly/JavaScript_interface/Memory) interface, and access an existing memory instance (currently you can only have one per module instance) using the associated instance methods. Memory instances have a [`buffer`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/buffer) getter, which returns an `ArrayBuffer` that points at the whole linear memory.
Memory instances can also grow, for example via the [`Memory.grow()`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/grow) method in JavaScript. When growth occurs, since `ArrayBuffer`s can't change size, the current `ArrayBuffer` is detached and a new `ArrayBuffer` is created to point to the newer, bigger memory. This means all we need to do to pass a string to JavaScript is to pass out the offset of the string in linear memory along with some way to indicate the length.
While there are many ways to encode a string's length in the string itself (for example, C strings); for simplicity here we just pass both offset and length as parameters:
```wasm
(import "console" "log" (func $log (param i32) (param i32)))
```
On the JavaScript side, we can use the [TextDecoder API](/en-US/docs/Web/API/TextDecoder) to easily decode our bytes into a JavaScript string. (We specify `utf8` here, but many other encodings are supported.)
```js
function consoleLogString(offset, length) {
const bytes = new Uint8Array(memory.buffer, offset, length);
const string = new TextDecoder("utf8").decode(bytes);
console.log(string);
}
```
The last missing piece of the puzzle is where `consoleLogString` gets access to the WebAssembly `memory`. WebAssembly gives us a lot of flexibility here: we can either create a [`Memory`](/en-US/docs/WebAssembly/JavaScript_interface/Memory) object in JavaScript and have the WebAssembly module import the memory, or we can have the WebAssembly module create the memory and export it to JavaScript.
For simplicity, let's create it in JavaScript then import it into WebAssembly. Our `import` statement is written as follows:
```wasm
(import "js" "mem" (memory 1))
```
The `1` indicates that the imported memory must have at least 1 page of memory (WebAssembly defines a page to be 64KB.)
So let's see a complete module that prints the string "Hi". In a normal compiled C program, you'd call a function to allocate some memory for the string, but since we're just writing our own assembly here and we own the entire linear memory, we can just write the string contents into global memory using a `data` section. Data sections allow a string of bytes to be written at a given offset at instantiation time and are similar to the `.data` sections in native executable formats.
Our final Wasm module looks like this:
```wasm
(module
(import "console" "log" (func $log (param i32 i32)))
(import "js" "mem" (memory 1))
(data (i32.const 0) "Hi")
(func (export "writeHi")
i32.const 0 ;; pass offset 0 to log
i32.const 2 ;; pass length 2 to log
call $log))
```
> **Note:** Above, note the double semicolon syntax (`;;`) for allowing comments in WebAssembly files.
Now from JavaScript we can create a Memory with 1 page and pass it in. This results in "Hi" being printed to the console:
```js
const memory = new WebAssembly.Memory({ initial: 1 });
const importObject = {
console: { log: consoleLogString },
js: { mem: memory },
};
WebAssembly.instantiateStreaming(fetch("logger2.wasm"), importObject).then(
(obj) => {
obj.instance.exports.writeHi();
},
);
```
> **Note:** You can find the full source on GitHub as [logger2.html](https://github.com/mdn/webassembly-examples/blob/main/understanding-text-format/logger2.html) ([also see it live](https://mdn.github.io/webassembly-examples/understanding-text-format/logger2.html)).
### WebAssembly tables
To finish this tour of the WebAssembly text format, let's look at the most intricate, and often confusing, part of WebAssembly: **tables**. Tables are basically resizable arrays of references that can be accessed by index from WebAssembly code.
To see why tables are needed, we need to first observe that the `call` instruction we saw earlier (see [Calling functions from other functions in the same module](#calling_functions_from_other_functions_in_the_same_module)) takes a static function index and thus can only ever call one function β but what if the callee is a runtime value?
- In JavaScript, we see this all the time: functions are first-class values.
- In C/C++, we see this with function pointers.
- In C++, we see this with virtual functions.
WebAssembly needed a type of call instruction to achieve this, so we gave it `call_indirect`, which takes a dynamic function operand. The problem is that the only types we have to give operands in WebAssembly are (currently) `i32`/`i64`/`f32`/`f64`.
WebAssembly could add an `anyfunc` type ("any" because the type could hold functions of any signature), but unfortunately this `anyfunc` type couldn't be stored in linear memory for security reasons. Linear memory exposes the raw contents of stored values as bytes and this would allow Wasm content to arbitrarily observe and corrupt raw function addresses, which is something that cannot be allowed on the web.
The solution was to store function references in a table and pass around table indices instead, which are just i32 values. `call_indirect`'s operand can therefore be an i32 index value.
#### Defining a table in Wasm
So how do we place Wasm functions in our table? Just like `data` sections can be used to initialize regions of linear memory with bytes, `elem` sections can be used to initialize regions of tables with functions:
```wasm
(module
(table 2 funcref)
(elem (i32.const 0) $f1 $f2)
(func $f1 (result i32)
i32.const 42)
(func $f2 (result i32)
i32.const 13)
...
)
```
- In `(table 2 funcref)`, the 2 is the initial size of the table (meaning it will store two references) and `funcref` declares that the element type of these references are function reference.
- The functions (`func`) sections are just like any other declared Wasm functions. These are the functions we are going to refer to in our table (for example's sake, each one just returns a constant value). Note that the order the sections are declared in doesn't matter here β you can declare your functions anywhere and still refer to them in your `elem` section.
- The `elem` section can list any subset of the functions in a module, in any order, allowing duplicates. This is a list of the functions that are to be referenced by the table, in the order they are to be referenced.
- The `(i32.const 0)` value inside the `elem` section is an offset β this needs to be declared at the start of the section, and specifies at what index in the table function references start to be populated. Here we've specified 0, and a size of 2 (see above), so we can fill in two references at indexes 0 and 1. If we wanted to start writing our references at offset 1, we'd have to write `(i32.const 1)`, and the table size would have to be 3.
> **Note:** Uninitialized elements are given a default throw-on-call value.
In JavaScript, the equivalent calls to create such a table instance would look something like this:
```js
function () {
// table section
const tbl = new WebAssembly.Table({initial: 2, element: "anyfunc"});
// function sections:
const f1 = ... /* some imported WebAssembly function */
const f2 = ... /* some imported WebAssembly function */
// elem section
tbl.set(0, f1);
tbl.set(1, f2);
};
```
#### Using the table
Moving on, now we've defined the table we need to use it somehow. Let's use this section of code to do so:
```wasm
(type $return_i32 (func (result i32))) ;; if this was f32, type checking would fail
(func (export "callByIndex") (param $i i32) (result i32)
local.get $i
call_indirect (type $return_i32))
```
- The `(type $return_i32 (func (result i32)))` block specifies a type, with a reference name. This type is used when performing type checking of the table function reference calls later on. Here we are saying that the references need to be functions that return an `i32` as a result.
- Next, we define a function that will be exported with the name `callByIndex`. This will take one `i32` as a parameter, which is given the argument name `$i`.
- Inside the function, we add one value to the stack β whatever value is passed in as the parameter `$i`.
- Finally, we use `call_indirect` to call a function from the table β it implicitly pops the value of `$i` off the stack. The net result of this is that the `callByIndex` function invokes the `$i`'th function in the table.
You could also declare the `call_indirect` parameter explicitly during the command call instead of before it, like this:
```wasm
(call_indirect (type $return_i32) (local.get $i))
```
In a higher level, more expressive language like JavaScript, you could imagine doing the same thing with an array (or probably more likely, object) containing functions. The pseudocode would look something like `tbl[i]()`.
So, back to the typechecking. Since WebAssembly is type checked, and the `funcref` can be potentially any function signature, we have to supply the presumed signature of the callee at the callsite, hence we include the `$return_i32` type, to tell the program a function returning an `i32` is expected. If the callee doesn't have a matching signature (say an `f32` is returned instead), a [`WebAssembly.RuntimeError`](/en-US/docs/WebAssembly/JavaScript_interface/RuntimeError) is thrown.
So what links the `call_indirect` to the table we are calling? The answer is that there is only one table allowed right now per module instance, and that is what `call_indirect` is implicitly calling. In the future, when multiple tables are allowed, we would also need to specify a table identifier of some kind, along the lines of
```wasm
call_indirect $my_spicy_table (type $i32_to_void)
```
The full module all together looks like this, and can be found in our [wasm-table.wat](https://github.com/mdn/webassembly-examples/blob/main/understanding-text-format/wasm-table.wat) example file:
```wasm
(module
(table 2 funcref)
(func $f1 (result i32)
i32.const 42)
(func $f2 (result i32)
i32.const 13)
(elem (i32.const 0) $f1 $f2)
(type $return_i32 (func (result i32)))
(func (export "callByIndex") (param $i i32) (result i32)
local.get $i
call_indirect (type $return_i32))
)
```
We load it into a webpage using the following JavaScript:
```js
WebAssembly.instantiateStreaming(fetch("wasm-table.wasm")).then((obj) => {
console.log(obj.instance.exports.callByIndex(0)); // returns 42
console.log(obj.instance.exports.callByIndex(1)); // returns 13
console.log(obj.instance.exports.callByIndex(2)); // returns an error, because there is no index position 2 in the table
});
```
> **Note:** You can find this example on GitHub as [wasm-table.html](https://github.com/mdn/webassembly-examples/blob/main/understanding-text-format/wasm-table.html) ([see it live also](https://mdn.github.io/webassembly-examples/understanding-text-format/wasm-table.html)).
> **Note:** Just like Memory, Tables can also be created from JavaScript (see [`WebAssembly.Table()`](/en-US/docs/WebAssembly/JavaScript_interface/Table)) as well as imported to/from another Wasm module.
### Mutating tables and dynamic linking
Because JavaScript has full access to function references, the Table object can be mutated from JavaScript using the [`grow()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/grow), [`get()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/get) and [`set()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/set) methods. And WebAssembly code is itself able to manipulate tables using instructions added as part of [Reference types](#reference_types), such as `table.get` and `table.set`.
Because tables are mutable, they can be used to implement sophisticated load-time and run-time [dynamic linking schemes](https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md). When a program is dynamically linked, multiple instances share the same memory and table. This is symmetric to a native application where multiple compiled `.dll`s share a single process's address space.
To see this in action, we'll create a single import object containing a Memory object and a Table object, and pass this same import object to multiple [`instantiate()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static) calls.
Our `.wat` examples look like so:
`shared0.wat`:
```wasm
(module
(import "js" "memory" (memory 1))
(import "js" "table" (table 1 funcref))
(elem (i32.const 0) $shared0func)
(func $shared0func (result i32)
i32.const 0
i32.load)
)
```
`shared1.wat`:
```wasm
(module
(import "js" "memory" (memory 1))
(import "js" "table" (table 1 funcref))
(type $void_to_i32 (func (result i32)))
(func (export "doIt") (result i32)
i32.const 0
i32.const 42
i32.store ;; store 42 at address 0
i32.const 0
call_indirect (type $void_to_i32))
)
```
These work as follows:
1. The function `shared0func` is defined in `shared0.wat`, and stored in our imported table.
2. This function creates a constant containing the value `0`, and then uses the `i32.load` command to load the value contained in the provided memory index. The index provided is `0` β again, it implicitly pops the previous value off the stack. So `shared0func` loads and returns the value stored at memory index `0`.
3. In `shared1.wat`, we export a function called `doIt` β this function creates two constants containing the values `0` and `42`, then calls `i32.store` to store a provided value at a provided index of the imported memory. Again, it implicitly pops these values off the stack, so the result is that it stores the value `42` in memory index `0`,
4. In the last part of the function, we create a constant with value `0`, then call the function at this index 0 of the table, which is `shared0func`, stored there earlier by the `elem` block in `shared0.wat`.
5. When called, `shared0func` loads the `42` we stored in memory using the `i32.store` command in `shared1.wat`.
> **Note:** The above expressions again pop values from the stack implicitly, but you could declare these explicitly inside the command calls instead, for example:
>
> ```wasm
> (i32.store (i32.const 0) (i32.const 42))
> (call_indirect (type $void_to_i32) (i32.const 0))
> ```
After converting to assembly, we then use `shared0.wasm` and `shared1.wasm` in JavaScript via the following code:
```js
const importObj = {
js: {
memory: new WebAssembly.Memory({ initial: 1 }),
table: new WebAssembly.Table({ initial: 1, element: "anyfunc" }),
},
};
Promise.all([
WebAssembly.instantiateStreaming(fetch("shared0.wasm"), importObj),
WebAssembly.instantiateStreaming(fetch("shared1.wasm"), importObj),
]).then((results) => {
console.log(results[1].instance.exports.doIt()); // prints 42
});
```
Each of the modules that is being compiled can import the same memory and table objects and thus share the same linear memory and table "address space".
> **Note:** You can find this example on GitHub as [shared-address-space.html](https://github.com/mdn/webassembly-examples/blob/main/understanding-text-format/shared-address-space.html) ([see it live also](https://mdn.github.io/webassembly-examples/understanding-text-format/shared-address-space.html)).
## Bulk memory operations
Bulk memory operations are a newer addition to the language (for example, in [Firefox 79](/en-US/docs/Mozilla/Firefox/Releases/79)) β seven new built-in operations are provided for bulk memory operations such as copying and initializing, to allow WebAssembly to model native functions such as `memcpy` and `memmove` in a more efficient, performant way.
The new operations are:
- `data.drop`: Discard the data in an data segment.
- `elem.drop`: Discard the data in an element segment.
- `memory.copy`: Copy from one region of linear memory to another.
- `memory.fill`: Fill a region of linear memory with a given byte value.
- `memory.init`: Copy a region from a data segment.
- `table.copy`: Copy from one region of a table to another.
- `table.init`: Copy a region from an element segment.
> **Note:** You can find more information in the [Bulk Memory Operations and Conditional Segment Initialization](https://github.com/WebAssembly/bulk-memory-operations/blob/master/proposals/bulk-memory-operations/Overview.md) proposal.
## Types
### Number types
WebAssembly currently has four available _number types_:
- `i32`: 32-bit integer
- `i64`: 64-bit integer
- `f32`: 32-bit float
- `f64`: 64-bit float
### Vector types
- `v128`: 128 bit vector of packed integer, floating-point data, or a single 128 bit type.
### Reference types
The [reference types proposal](https://github.com/WebAssembly/reference-types/blob/master/proposals/reference-types/Overview.md) (supported in [Firefox 79](/en-US/docs/Mozilla/Firefox/Releases/79)) provides two main features:
- A new type, `externref`, which can hold _any_ JavaScript value, for example strings, DOM references, objects, etc. `externref` is opaque from the point of view of WebAssembly β a Wasm module can't access and manipulate these values and instead can only receive them and pass them back out. But this is very useful for allowing Wasm modules to call JavaScript functions, DOM APIs, etc., and generally to pave the way for easier interoperability with the host environment. `externref` can be used for value types and table elements.
- A number of new instructions that allow Wasm modules to directly manipulate [WebAssembly tables](#webassembly_tables), rather than having to do it via the JavaScript API.
> **Note:** The [wasm-bindgen](https://rustwasm.github.io/docs/wasm-bindgen/) documentation contains some useful information on how to take advantage of `externref` from Rust.
## Multi-value WebAssembly
Another more recent addition to the language (for example, in [Firefox 78](/en-US/docs/Mozilla/Firefox/Releases/78)) is WebAssembly multi-value, meaning that WebAssembly functions can now return multiple values, and instruction sequences can consume and produce multiple stack values.
At the time of writing (June 2020) this is at an early stage, and the only multi-value instructions available are calls to functions that themselves return multiple values. For example:
```wasm
(module
(func $get_two_numbers (result i32 i32)
i32.const 1
i32.const 2
)
(func (export "add_two_numbers") (result i32)
call $get_two_numbers
i32.add
)
)
```
But this will pave the way for more useful instruction types, and other things besides. For a useful write-up of progress so far and how this works, see [Multi-Value All The Wasm!](https://hacks.mozilla.org/2019/11/multi-value-all-the-wasm/) by Nick Fitzgerald.
## WebAssembly threads
WebAssembly Threads (supported in [Firefox 79](/en-US/docs/Mozilla/Firefox/Releases/79) onwards) allow WebAssembly Memory objects to be shared across multiple WebAssembly instances running in separate Web Workers, in the same fashion as [`SharedArrayBuffer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer)s in JavaScript. This allows very fast communication between Workers, and significant performance gains in web applications.
The threads proposal has two parts, shared memories and atomic memory accesses.
### Shared memories
As described above, you can create shared WebAssembly [`Memory`](/en-US/docs/WebAssembly/JavaScript_interface/Memory) objects, which can be transferred between Window and Worker contexts using [`postMessage()`](/en-US/docs/Web/API/Window/postMessage), in the same fashion as a [`SharedArrayBuffer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer).
Over on the JavaScript API side, the [`WebAssembly.Memory()`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/Memory) constructor's initialization object now has a `shared` property, which when set to `true` will create a shared memory:
```js
const memory = new WebAssembly.Memory({
initial: 10,
maximum: 100,
shared: true,
});
```
the memory's [`buffer`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/buffer) property will now return a `SharedArrayBuffer`, instead of the usual `ArrayBuffer`:
```js
memory.buffer; // returns SharedArrayBuffer
```
Over in the text format, you can create a shared memory using the `shared` keyword, like this:
```wasm
(memory 1 2 shared)
```
Unlike unshared memories, shared memories must specify a "maximum" size, in both the JavaScript API constructor and Wasm text format.
> **Note:** You can find a lot more details in the [Threading proposal for WebAssembly](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md).
### Atomic memory accesses
A number of new Wasm instructions have been added that can be used to implement higher level features like mutexes, condition variables, etc. You can [find them listed here](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#atomic-memory-accesses). These instructions are allowed on non-shared memories as of Firefox 80.
> **Note:** The [Emscripten Pthreads support page](https://emscripten.org/docs/porting/pthreads.html) shows how to take advantage of this new functionality from Emscripten.
## Summary
This finishes our high-level tour of the major components of the WebAssembly text format and how they get reflected in the WebAssembly JS API.
## See also
- The main thing that wasn't included is a comprehensive list of all the instructions that can occur in function bodies. See the [WebAssembly semantics](https://webassembly.github.io/spec/core/exec/index.html) for a treatment of each instruction.
- See also the [grammar of the text format](https://github.com/WebAssembly/spec/blob/master/interpreter/README.md#s-expression-syntax) that is implemented by the spec interpreter.
| 0 |
data/mdn-content/files/en-us/webassembly | data/mdn-content/files/en-us/webassembly/javascript_interface/index.md | ---
title: WebAssembly
slug: WebAssembly/JavaScript_interface
page-type: webassembly-interface
browser-compat: webassembly.api
---
{{WebAssemblySidebar}}
The **`WebAssembly`** JavaScript object acts as the namespace for all [WebAssembly](/en-US/docs/WebAssembly)-related functionality.
Unlike most other global objects, `WebAssembly` is not a constructor (it is not a function object). You can compare it to {{jsxref("Math")}}, which is also a namespace object for mathematical constants and functions, or to {{jsxref("Intl")}} which is the namespace object for internationalization constructors and other language-sensitive functions.
## Description
The primary uses for the `WebAssembly` object are:
- Loading WebAssembly code, using the [`WebAssembly.instantiate()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static) function.
- Creating new memory and table instances via the [`WebAssembly.Memory()`](/en-US/docs/WebAssembly/JavaScript_interface/Memory)/[`WebAssembly.Table()`](/en-US/docs/WebAssembly/JavaScript_interface/Table) constructors.
- Providing facilities to handle errors that occur in WebAssembly via the [`WebAssembly.CompileError()`](/en-US/docs/WebAssembly/JavaScript_interface/CompileError)/[`WebAssembly.LinkError()`](/en-US/docs/WebAssembly/JavaScript_interface/LinkError)/[`WebAssembly.RuntimeError()`](/en-US/docs/WebAssembly/JavaScript_interface/RuntimeError) constructors.
## Constructor properties
- [`WebAssembly.CompileError()`](/en-US/docs/WebAssembly/JavaScript_interface/CompileError/CompileError)
- : Indicates an error during WebAssembly decoding or validation.
- [`WebAssembly.Global()`](/en-US/docs/WebAssembly/JavaScript_interface/Global/Global)
- : Represents a global variable instance, accessible from both JavaScript and importable/exportable across one or more [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) instances. This allows dynamic linking of multiple modules.
- [`WebAssembly.Instance()`](/en-US/docs/WebAssembly/JavaScript_interface/Instance/Instance)
- : Is a stateful, executable instance of a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module)
- [`WebAssembly.LinkError()`](/en-US/docs/WebAssembly/JavaScript_interface/LinkError/LinkError)
- : Indicates an error during module instantiation (besides [traps](https://webassembly.github.io/simd/core/intro/overview.html#trap) from the start function).
- [`WebAssembly.Memory()`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/Memory)
- : An object whose [`buffer`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/buffer) property is a resizable {{jsxref("ArrayBuffer")}} that holds the raw bytes of memory accessed by a WebAssembly `Instance`.
- [`WebAssembly.Module()`](/en-US/docs/WebAssembly/JavaScript_interface/Module/Module)
- : Contains stateless WebAssembly code that has already been compiled by the browser and can be efficiently [shared with Workers](/en-US/docs/Web/API/Worker/postMessage), and instantiated multiple times.
- [`WebAssembly.RuntimeError()`](/en-US/docs/WebAssembly/JavaScript_interface/RuntimeError/RuntimeError)
- : Error type that is thrown whenever WebAssembly specifies a [trap](https://webassembly.github.io/spec/core/exec/index.html).
- [`WebAssembly.Table()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/Table)
- : An array-like structure representing a WebAssembly Table, which stores [references](https://webassembly.github.io/spec/core/syntax/types.html#syntax-reftype), such as function references.
- [`WebAssembly.Tag()`](/en-US/docs/WebAssembly/JavaScript_interface/Tag/Tag)
- : An object that represents a type of WebAssembly exception.
- [`WebAssembly.Exception()`](/en-US/docs/WebAssembly/JavaScript_interface/Exception/Exception)
- : A WebAssembly exception object that can be thrown, caught, and rethrown both within and across WebAssembly/JavaScript boundaries.
## Static methods
- [`WebAssembly.instantiate()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static)
- : The primary API for compiling and instantiating WebAssembly code, returning both a `Module` and its first `Instance`.
- [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static)
- : Compiles and instantiates a WebAssembly module directly from a streamed underlying source, returning both a `Module` and its first `Instance`.
- [`WebAssembly.compile()`](/en-US/docs/WebAssembly/JavaScript_interface/compile_static)
- : Compiles a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) from WebAssembly binary code, leaving instantiation as a separate step.
- [`WebAssembly.compileStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/compileStreaming_static)
- : compiles a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) directly from a streamed underlying source, leaving instantiation as a separate step.
- [`WebAssembly.validate()`](/en-US/docs/WebAssembly/JavaScript_interface/validate_static)
- : Validates a given typed array of WebAssembly binary code, returning whether the bytes are valid WebAssembly code (`true`) or not (`false`).
## Examples
### Stream a Wasm module then compile and instantiate it
The following example (see our [instantiate-streaming.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/instantiate-streaming.html) demo on GitHub, and [view it live](https://mdn.github.io/webassembly-examples/js-api-examples/instantiate-streaming.html) also) directly streams a Wasm module from an underlying source then compiles and instantiates it, the promise fulfilling with a `ResultObject`. Because the `instantiateStreaming()` function accepts a promise for a [`Response`](/en-US/docs/Web/API/Response) object, you can directly pass it a [`fetch()`](/en-US/docs/Web/API/fetch) call, and it will pass the response into the function when it fulfills.
```js
const importObject = { imports: { imported_func: (arg) => console.log(arg) } };
WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
(obj) => obj.instance.exports.exported_func(),
);
```
The `ResultObject`'s `.instance` property is then accessed, and the contained exported function invoked.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/runtimeerror/index.md | ---
title: WebAssembly.RuntimeError
slug: WebAssembly/JavaScript_interface/RuntimeError
page-type: webassembly-interface
browser-compat: webassembly.api.RuntimeError
---
{{WebAssemblySidebar}}
The **`WebAssembly.RuntimeError`** object is the error type that is thrown whenever WebAssembly specifies a [trap](https://webassembly.github.io/spec/core/intro/overview.html#trap).
## Constructor
- [`WebAssembly.RuntimeError()`](/en-US/docs/WebAssembly/JavaScript_interface/RuntimeError/RuntimeError)
- : Creates a new `WebAssembly.RuntimeError` object.
## Instance properties
- {{jsxref("Error.prototype.message", "WebAssembly.RuntimeError.prototype.message")}}
- : Error message. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.name", "WebAssembly.RuntimeError.prototype.name")}}
- : Error name. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.cause", "WebAssembly.RuntimeError.prototype.cause")}}
- : Error cause. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.fileName", "WebAssembly.RuntimeError.prototype.fileName")}} {{non-standard_inline}}
- : Path to file that raised this error. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.lineNumber", "WebAssembly.RuntimeError.prototype.lineNumber")}} {{non-standard_inline}}
- : Line number in file that raised this error. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.columnNumber", "WebAssembly.RuntimeError.prototype.columnNumber")}} {{non-standard_inline}}
- : Column number in line that raised this error. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.stack", "WebAssembly.RuntimeError.prototype.stack")}} {{non-standard_inline}}
- : Stack trace. Inherited from {{jsxref("Error")}}.
## Instance methods
- {{jsxref("Error.prototype.toString", "WebAssembly.RuntimeError.prototype.toString()")}}
- : Returns a string representing the specified `Error` object. Inherited from {{jsxref("Error")}}.
## Examples
### Creating a new RuntimeError instance
The following snippet creates a new `RuntimeError` instance, and logs its details to the console:
```js
try {
throw new WebAssembly.RuntimeError("Hello", "someFile", 10);
} catch (e) {
console.log(e instanceof WebAssembly.RuntimeError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "RuntimeError"
console.log(e.fileName); // "someFile"
console.log(e.lineNumber); // 10
console.log(e.columnNumber); // 0
console.log(e.stack); // returns the location where the code was run
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/runtimeerror | data/mdn-content/files/en-us/webassembly/javascript_interface/runtimeerror/runtimeerror/index.md | ---
title: WebAssembly.RuntimeError() constructor
slug: WebAssembly/JavaScript_interface/RuntimeError/RuntimeError
page-type: webassembly-constructor
browser-compat: webassembly.api.RuntimeError.RuntimeError
---
{{WebAssemblySidebar}}
The **`WebAssembly.RuntimeError()`** constructor creates a new
WebAssembly `RuntimeError` object β the type that is thrown whenever
WebAssembly specifies a [trap](https://webassembly.github.io/simd/core/intro/overview.html#trap).
## Syntax
```js-nolint
new WebAssembly.RuntimeError()
new WebAssembly.RuntimeError(message)
new WebAssembly.RuntimeError(message, options)
new WebAssembly.RuntimeError(message, fileName)
new WebAssembly.RuntimeError(message, fileName, lineNumber)
```
### Parameters
- `message` {{optional_inline}}
- : Human-readable description of the error.
- `options` {{optional_inline}}
- : An object that has the following properties:
- `cause` {{optional_inline}}
- : A property indicating the specific cause of the error.
When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.
- `fileName` {{optional_inline}} {{non-standard_inline}}
- : The name of the file containing the code that caused the exception.
- `lineNumber` {{optional_inline}} {{non-standard_inline}}
- : The line number of the code that caused the exception.
## Examples
### Creating a new RuntimeError instance
The following snippet creates a new `RuntimeError` instance, and logs its
details to the console:
```js
try {
throw new WebAssembly.RuntimeError("Hello", "someFile", 10);
} catch (e) {
console.log(e instanceof WebAssembly.RuntimeError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "RuntimeError"
console.log(e.fileName); // "someFile"
console.log(e.lineNumber); // 10
console.log(e.columnNumber); // 0
console.log(e.stack); // returns the location where the code was run
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/exception/index.md | ---
title: WebAssembly.Exception
slug: WebAssembly/JavaScript_interface/Exception
page-type: webassembly-interface
browser-compat: webassembly.api.Exception
---
{{WebAssemblySidebar}}
The **`WebAssembly.Exception`** object represents a runtime exception thrown from WebAssembly to JavaScript, or thrown from JavaScript to a WebAssembly exception handler.
The [constructor](/en-US/docs/WebAssembly/JavaScript_interface/Exception/Exception) accepts a [`WebAssembly.Tag`](/en-US/docs/WebAssembly/JavaScript_interface/Tag), an array of values, and an `options` object as arguments.
The tag uniquely defines the _type_ of an exception, including the order of its arguments and their data types.
The same tag that was used to create the `Exception` is required to access the arguments of a thrown exception.
Methods are provided to test whether an exception matches a particular tag, and also to get a particular value by index (if the exception matches specified tag).
JavaScript and other client code can only access WebAssembly exception values, and visa versa, when the associated tag is shared (you can't just use another tag that happens to define the same data types).
Without the matching tag, exceptions can be caught and re-thrown, but they can't be inspected.
In order to make exception-throwing faster, exceptions thrown from WebAssembly generally do not include a stack trace.
WebAssembly code that needs to provide a stack trace must call a JavaScript function to create the exception, passing `options.traceStack=true` parameter in the constructor.
The constructor may then return an exception with a stack trace attached to the [`stack`](/en-US/docs/WebAssembly/JavaScript_interface/Exception/stack) property.
{{AvailableInWorkers}}
## Constructor
- [`WebAssembly.Exception()`](/en-US/docs/WebAssembly/JavaScript_interface/Exception/Exception)
- : Creates a new `WebAssembly.Exception` object.
## Instance methods
- [`Exception.prototype.is()`](/en-US/docs/WebAssembly/JavaScript_interface/Exception/is)
- : Tests whether the exception matches a particular tag.
- [`Exception.prototype.getArg()`](/en-US/docs/WebAssembly/JavaScript_interface/Exception/getArg)
- : Returns the data fields of an exception that matches a specified tag.
## Instance properties
- [`Exception.prototype.stack`](/en-US/docs/WebAssembly/JavaScript_interface/Exception/stack) {{non-standard_inline}}
- : Returns the stack trace for the exception, or `undefined`.
## Examples
This example shows how to define a tag and import it into a module, then use it to throw an exception that is caught in JavaScript.
Consider the following WebAssembly code, which is assumed to be compiled to a file **example.wasm**.
- The module imports a tag that is referred to as `$tagname` internally and that has a single `i32` parameter.
The tag expects the tag to be passed using module `extmod` and tag `exttag`.
- The `$throwException` function throws an exception using the `throw` instruction, taking the `$tagname` and the parameter argument.
- The module exports the function `run()` that throws an exception with the value "42".
```wasm
(module
;; import tag that will be referred to here as $tagname
(import "extmod" "exttag" (tag $tagname (param i32)))
;; $throwException function throws i32 param as a $tagname exception
(func $throwException (param $errorValueArg i32)
local.get $errorValueArg
throw $tagname
)
;; Exported function "run" that calls $throwException
(func (export "run")
i32.const 42
call $throwException
)
)
```
The code below calls [`WebAssembly.instantiateStreaming`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) to import the **example.wasm** file, passing in an "import object" (`importObject`) that includes a new [`WebAssembly.Tag`](/en-US/docs/WebAssembly/JavaScript_interface/Tag) named `tagToImport`.
The import object defines an object with properties that match the `import` statement in the WebAssembly code.
Once the file is instantiated, the code calls the exported WebAssembly `run()` method, which will immediately throw an exception.
```js
const tagToImport = new WebAssembly.Tag({ parameters: ["i32"] });
// Note: import object properties match the WebAssembly import statement!
const importObject = {
extmod: {
exttag: tagToImport,
},
};
WebAssembly.instantiateStreaming(fetch("example.wasm"), importObject)
.then((obj) => {
console.log(obj.instance.exports.run());
})
.catch((e) => {
console.error(e);
// Check we have the right tag for the exception
// If so, use getArg() to inspect it
if (e.is(tagToImport)) {
console.log(`getArg 0 : ${e.getArg(tagToImport, 0)}`);
}
});
/* Log output
example.js:40 WebAssembly.Exception: wasm exception
example.js:41 getArg 0 : 42
*/
```
The exception is caught in JavaScript using the `catch` block.
We can see it is of type `WebAssembly.Exception`, but if we didn't have the right tag we couldn't do much else.
However, because we have a tag, we use [`Exception.prototype.is()`](/en-US/docs/WebAssembly/JavaScript_interface/Exception/is) to check that it's the right one, and because it is correct, we call [`Exception.prototype.getArg()`](/en-US/docs/WebAssembly/JavaScript_interface/Exception/getArg) to read the value of "42".
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/exception | data/mdn-content/files/en-us/webassembly/javascript_interface/exception/getarg/index.md | ---
title: WebAssembly.Exception.prototype.getArg()
slug: WebAssembly/JavaScript_interface/Exception/getArg
page-type: webassembly-instance-method
browser-compat: webassembly.api.Exception.getArg
---
{{WebAssemblySidebar}}
The **`getArg()`** prototype method of the [`Exception`](/en-US/docs/WebAssembly/JavaScript_interface/Exception) object can be used to get the value of a specified item in the exception's data arguments.
The method passes a [`WebAssembly.Tag`](/en-US/docs/WebAssembly/JavaScript_interface/Tag) and will only succeed if the thrown `Exception` was created using the same tag, otherwise it will throw a `TypeError`.
This ensures that the exception can only be read if the calling code has access to the tag.
Tags that are neither imported into or exported from the WebAssembly code are internal, and their associated [`WebAssembly.Exception`](/en-US/docs/WebAssembly/JavaScript_interface/Exception) cannot be queried using this method!
> **Note:** It is not enough that the tag has an identical sequence of data types β it must have the same _identity_ (be the same tag) as was used to create the exception.
## Syntax
```js-nolint
getArg(exceptionTag, index)
```
### Parameters
- `exceptionTag`
- : A [`WebAssembly.Tag`](/en-US/docs/WebAssembly/JavaScript_interface/Tag) that must match the tag associated with this exception.
- `index`
- : The index of the value in the data arguments to return, 0-indexed.
### Return value
The value of the argument at `index`.
### Exceptions
- {{jsxref("TypeError")}}
- : The tags don't match; the exception was not created with the tag passed to the method.
- {{jsxref("RangeError")}}
- : The value of the `index` parameter is greater than or equal to the number of fields in the data.
## Examples
In order to get the values of an exception, the tag must be "known" to the calling code;
it may be either imported into or exported from the calling code.
### Getting exception value from imported tag
Consider the following WebAssembly code, which is assumed to be compiled to a file "example.wasm".
This imports a tag, which it refers to internally as `$tagname`, and exports a method `run` that can be called by external code to throw an exception using the tag.
```wasm
(module
;; import tag that will be referred to here as $tagname
(import "extmod" "exttag" (tag $tagname (param i32)))
;; $throwException function throws i32 param as a $tagname exception
(func $throwException (param i32)
local.get 0
throw $tagname
)
;; Exported function "run" that calls $throwException
(func (export "run")
i32.const 1
call $throwException
)
)
```
The code below calls [`WebAssembly.instantiateStreaming`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) to import the "example.wasm" file, passing in an "import object" (`importObject`) that includes a new [`WebAssembly.Tag`](/en-US/docs/WebAssembly/JavaScript_interface/Tag) named `tagToImport`.
The import object defines an object with properties that match the `import` statement in the WebAssembly code.
Once the file is instantiated, the code calls the exported WebAssembly `run()` method, which will immediately throw an exception.
```js
const tagToImport = new WebAssembly.Tag({ parameters: ["i32"] });
// Note: the import object properties match the import statement in WebAssembly code!
const importObject = {
extmod: {
exttag: tagToImport,
},
};
WebAssembly.instantiateStreaming(fetch("example.wasm"), importObject)
.then((obj) => {
console.log(obj.instance.exports.run());
})
.catch((e) => {
console.error(e);
console.log(`getArg 0 : ${e.getArg(tagToImport, 0)}`);
});
/* Log output
example.js:40 WebAssembly.Exception: wasm exception
example.js:41 getArg 0 : 1
*/
```
The code catches the exception and uses `getArg()` to print the value at the first index.
In this case, it is just "1".
### Getting exception value from an exported tag
The process for using an exported tag is very similar to that shown in the previous section.
Here is the same WebAssembly module, simply replacing the import with an export.
```wasm
(module
;; Export tag giving it external name: "exptag"
(tag $tagname (export "exptag") (param i32))
(func $throwException (param i32)
local.get 0
throw $tagname
)
(func (export "run")
i32.const 1
call $throwException
)
)
```
The JavaScript is similar too. In this case, we have no imports, but instead we get the exported tag and use that to get the argument.
To make it a little more "safe", here we also test that we have the right tag using the [`is()` method](/en-US/docs/WebAssembly/JavaScript_interface/Exception/is).
```js
let tagExportedFromWasm;
WebAssembly.instantiateStreaming(fetch("example.wasm"))
.then((obj) => {
// Import the tag using its name from the WebAssembly module
tagExportedFromWasm = obj.instance.exports.exptag;
console.log(obj.instance.exports.run());
})
.catch((e) => {
console.error(e);
// If the tag is correct, get the value
if (e.is(tagExportedFromWasm)) {
console.log(`getArg 0 : ${e.getArg(tagExportedFromWasm, 0)}`);
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/exception | data/mdn-content/files/en-us/webassembly/javascript_interface/exception/exception/index.md | ---
title: WebAssembly.Exception constructor
slug: WebAssembly/JavaScript_interface/Exception/Exception
page-type: webassembly-constructor
browser-compat: webassembly.api.Exception.Exception
---
{{WebAssemblySidebar}}
The **`WebAssembly.Exception()`** constructor is used to create a new [`WebAssembly.Exception`](/en-US/docs/WebAssembly/JavaScript_interface/Exception).
The constructor accepts a [`Tag`](/en-US/docs/WebAssembly/JavaScript_interface/Exception) argument and a `payload` array of data fields.
The data types of each of the payload elements must match the corresponding data type specified in the `Tag`.
The constructor may also take an `options` object.
The `options.traceStack` property can be set `true` (by default it is `false`) to indicate that a Wasm stack trace may be attached to the exception's [`stack`](/en-US/docs/WebAssembly/JavaScript_interface/Exception/stack) property.
## Syntax
```js-nolint
new Exception(tag, payload)
new Exception(tag, payload, options)
```
### Parameters
- `tag`
- : An [`WebAssembly.Tag`](/en-US/docs/WebAssembly/JavaScript_interface/Tag) defining the data types expected for each of the values in the `payload`.
- `payload`
- : An array of one or more data fields comprising the payload of the exception.
The elements must match the data types of the corresponding elements in the `tag`.
If the number of data fields in the payload and their types don't match, a {{jsxref("TypeError")}} exception is thrown.
- `options` {{optional_inline}} {{non-standard_inline}}
- : An object with the following optional fields:
- `traceStack` {{optional_inline}} {{non-standard_inline}}
- : `true` if the `Exception` may have a stack trace attached to its [`stack`](/en-US/docs/WebAssembly/JavaScript_interface/Exception/stack) property, otherwise `false`.
This is `false` by default (if `options` or `options.traceStack` are not provided).
### Exceptions
- `TypeError`
- : The `payload` and `tag` sequences do not have the same number of elements and/or the elements are not of matching types.
## Examples
This example shows the creation of an exception using a simple tag.
```js
// Create tag and use it to create an exception
const tag = new WebAssembly.Tag({ parameters: ["i32", "f32"] });
const exception = new WebAssembly.Exception(tag, [42, 42.3]);
```
The [`stack` example](/en-US/docs/WebAssembly/JavaScript_interface/Exception/stack#examples) shows the creation of an exception that uses the `options` parameter.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/exception | data/mdn-content/files/en-us/webassembly/javascript_interface/exception/stack/index.md | ---
title: WebAssembly.Exception.prototype.stack
slug: WebAssembly/JavaScript_interface/Exception/stack
page-type: webassembly-instance-property
status:
- non-standard
browser-compat: webassembly.api.Exception.stack
---
{{WebAssemblySidebar}} {{non-standard_header}}
The read-only **`stack`** property of an object instance of type [`WebAssembly.Exception`](/en-US/docs/WebAssembly/JavaScript_interface/Exception) _may_ contain a stack trace.
Exceptions from WebAssembly code do not include a stack trace by default.
If WebAssembly code needs to provide a stack trace, it must call a JavaScript function to create the exception, passing `options.traceStack=true` parameter in the [constructor](/en-US/docs/WebAssembly/JavaScript_interface/Exception/Exception).
The virtual machine can then attach a stack trace to the exception object returned by the constructor.
> **Note:** Stack traces are not normally sent from WebAssembly code to improve performance.
> The ability to add stack traces to these exceptions is provided for developer tooling, and is not generally recommended for broader use.
## Value
A string containing the stack trace, or {{jsxref("undefined")}} if no trace has been assigned.
The stack trace string lists the locations of each operation on the stack in WebAssembly format.
This is a human-readable string indicating the URL, name of the function type called, the function index, and its offset in the module binary.
It has approximately this format (see [stack trace conventions](https://webassembly.github.io/spec/web-api/index.html#conventions) in the specification for more information):
```plain
${url}:wasm-function[${funcIndex}]:${pcOffset}
```
## Examples
This example demonstrate how to throw an exception from WebAssembly that includes a stack trace.
Consider the following WebAssembly code, which is assumed to be compiled to a file named **example.wasm**.
This imports a tag, which it refers to as `$tagname` internally, and imports a function that it refers to as `$throwExnWithStack`.
It exports the method `run` that can be called by external code to call `$throwExnWithStack` (and hence the JavaScript function).
```wasm
(module
;; import tag that will be referred to here as $tagname
(import "extmod" "exttag" (tag $tagname (param i32)))
;; import function that will be referred to here as $throwExnWithStack
(import "extmod" "throwExnWithStack" (func $throwExnWithStack (param i32)))
;; call $throwExnWithStack passing 42 as parameter
(func (export "run")
i32.const 42
call $throwExnWithStack
)
)
```
The JavaScript code below defines a new tag `tag` and the function `throwExceptionWithStack`.
These are passed to the WebAssembly module in the `importObject` when it is instantiated.
Once the file is instantiated, the code calls the exported WebAssembly `run()` method, which will immediately throw an exception.
The stack is then logged from the `catch` statement.
```js
const tag = new WebAssembly.Tag({ parameters: ["i32"] });
function throwExceptionWithStack(param) {
// Note: We declare the exception with "{traceStack: true}"
throw new WebAssembly.Exception(tag, [param], { traceStack: true });
}
// Note: importObject properties match the WebAssembly import statements.
const importObject = {
extmod: {
exttag: tag,
throwExnWithStack: throwExceptionWithStack,
},
};
WebAssembly.instantiateStreaming(fetch("example.wasm"), importObject)
.then((obj) => {
console.log(obj.instance.exports.run());
})
.catch((e) => {
console.log(`stack: ${e.stack}`);
});
//Log output (something like):
// stack: throwExceptionWithStack@http://<url>/main.js:76:9
// @http://<url>/example.wasm:wasm-function[3]:0x73
// @http://<url>/main.js:82:38
```
The most "relevant" part of this code is the line where the exception is created:
```js
new WebAssembly.Exception(tag, [param], { traceStack: true });
```
Passing in `{traceStack: true}` tells the WebAssembly virtual machine that it should attach a stack trace to the returned `WebAssembly.Exception`.
Without this, the stack would be `undefined`.
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/exception | data/mdn-content/files/en-us/webassembly/javascript_interface/exception/is/index.md | ---
title: WebAssembly.Exception.prototype.is()
slug: WebAssembly/JavaScript_interface/Exception/is
page-type: webassembly-instance-method
browser-compat: webassembly.api.Exception.is
---
{{WebAssemblySidebar}}
The **`is()`** prototype method of the [`Exception`](/en-US/docs/WebAssembly/JavaScript_interface/Exception) object can be used to test if the `Exception` matches a given tag.
The method might be used to test that a tag is correct before passing it to [`Exception.prototype.getArg()`](/en-US/docs/WebAssembly/JavaScript_interface/Exception/getArg) to get the passed values.
It can be used on tags created in JavaScript or created in WebAssembly code and exported to JavaScript.
> **Note:** It is not enough that the tag has an identical sequence of data types β it must have the same _identity_ (be the same tag) as was used to create the exception.
## Syntax
```js-nolint
is(tag)
```
### Parameters
- `tag`
- : An [`WebAssembly.Tag`](/en-US/docs/WebAssembly/JavaScript_interface/Tag) that can be checked to verify the type of the exception.
### Return value
A boolean `true` if the specified tag matches the exception, and `false` otherwise.
## Examples
The code below shows how to use `is()` to verify that a tag matches an [`Exception`](/en-US/docs/WebAssembly/JavaScript_interface/Exception).
```js
// Create tag and use it to create an exception
const tag1 = new WebAssembly.Tag({ parameters: ["i32", "f64"] });
const exception1 = new WebAssembly.Exception(tag1, [42, 42.3]);
// Verify that "tag1" matches this exception
console.log(`Tag1: ${exception1.is(tag1)}`);
// Log output:
// Tag1: true
```
We can also demonstrate that this exception will not match another tag even if the tag is created with the same parameters.
```js
// Create a new tag (with same parameters) and verify it does not match the exception
const tag2 = new WebAssembly.Tag({ parameters: ["i32", "f64"] });
console.log(`Tag2: ${exception1.is(tag2)}`);
// Log output:
// Tag2: false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/compilestreaming_static/index.md | ---
title: WebAssembly.compileStreaming()
slug: WebAssembly/JavaScript_interface/compileStreaming_static
page-type: webassembly-function
browser-compat: webassembly.api.compileStreaming_static
---
{{WebAssemblySidebar}}
The **`WebAssembly.compileStreaming()`** static method compiles a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) directly from a streamed underlying source.
This function is useful if it is necessary to compile a module before it can be instantiated (otherwise, the [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) function should be used).
> **Note:** Webpages that have strict [Content Security Policy (CSP)](/en-US/docs/Web/HTTP/CSP) might block WebAssembly from compiling and executing modules.
> For more information on allowing WebAssembly compilation and execution, see the [script-src CSP](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src).
## Syntax
```js-nolint
WebAssembly.compileStreaming(source)
```
### Parameters
- `source`
- : A [`Response`](/en-US/docs/Web/API/Response) object or a promise that will fulfill with one, representing the underlying source of a Wasm module you want to stream and compile.
### Return value
A `Promise` that resolves to a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object representing the compiled module.
### Exceptions
- If `source` is not a [`Response`](/en-US/docs/Web/API/Response) or `Promise` resolving to a `Response`, the promise rejects with a {{jsxref("TypeError")}}.
- If compilation fails, the promise rejects with a [`WebAssembly.CompileError`](/en-US/docs/WebAssembly/JavaScript_interface/CompileError).
- If the `source` is a `Promise` that rejects, the promise rejects with the error.
- If the `source`'s `Result` has an error (e.g. bad MIME type), the promise rejects with an error.
## Examples
### Compile streaming
The following example (see our [compile-streaming.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/compile-streaming.html) demo on GitHub, and [view it live](https://mdn.github.io/webassembly-examples/js-api-examples/compile-streaming.html) also) directly streams a Wasm module from an underlying source then compiles it to a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object. Because the `compileStreaming()` function accepts a promise for a [`Response`](/en-US/docs/Web/API/Response) object, you can directly pass it a `Promise` from calling [`fetch()`](/en-US/docs/Web/API/fetch), without waiting for the promise to fulfill.
```js
const importObject = { imports: { imported_func: (arg) => console.log(arg) } };
WebAssembly.compileStreaming(fetch("simple.wasm"))
.then((module) => WebAssembly.instantiate(module, importObject))
.then((instance) => instance.exports.exported_func());
```
The resulting module instance is then instantiated using
[`WebAssembly.instantiate()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static), and the exported function invoked.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/tag/index.md | ---
title: WebAssembly.Tag
slug: WebAssembly/JavaScript_interface/Tag
page-type: webassembly-interface
browser-compat: webassembly.api.Tag
---
{{WebAssemblySidebar}}
The **`WebAssembly.Tag`** object defines a _type_ of a WebAssembly exception that can be thrown to/from WebAssembly code.
When creating a [`WebAssembly.Exception`](/en-US/docs/WebAssembly/JavaScript_interface/Exception), the tag defines the data types and order of the values carried by the exception.
The same unique tag instance must be used to access the values of the exception (for example, when using [`Exception.prototype.getArg()`](/en-US/docs/WebAssembly/JavaScript_interface/Exception/getArg)).
[Constructing](/en-US/docs/WebAssembly/JavaScript_interface/Tag/Tag) an instance of `Tag` creates a new unique tag.
This tag can be passed to a WebAssembly module as a tag import, where it will become a typed tag defined in the _tag section_ of the WebAssembly module.
You can also export a tag defined in a module and use it to inspect exceptions thrown from the module.
> **Note:** You can't access the values of an exception with a new tag that just happens to have the same parameters; it's a different tag!
> This ensures that WebAssembly modules can keep exception information internal if required.
> Code can still catch and rethrow exceptions that it does not understand.
## Constructor
- [`WebAssembly.Tag()`](/en-US/docs/WebAssembly/JavaScript_interface/Tag/Tag)
- : Creates a new `WebAssembly.Tag` object.
## Instance methods
- [`Tag.prototype.type()`](/en-US/docs/WebAssembly/JavaScript_interface/Tag/type)
- : Returns the object defining the data-types array for the tag (as set in its constructor).
## Examples
This code snippet creates a new `Tag` instance.
```js
const tagToImport = new WebAssembly.Tag({ parameters: ["i32", "f32"] });
```
The snippet below shows how we might pass it to a module **example.wasm** during instantiation, using an "import object".
```js
const importObject = {
extmod: {
exttag: tagToImport,
},
};
WebAssembly.instantiateStreaming(fetch("example.wasm"), importObject).then(
(obj) => {
// β¦
},
);
```
The WebAssembly module might then import the tag as shown below:
```wasm
(module
(import "extmod" "exttag" (tag $tagname (param i32 f32))
)
```
If the tag was used to throw an exception that propagated to JavaScript, we could use the tag to inspect its values.
> **Note:** There are many alternatives. We could also use the tag to create a [`WebAssembly.Exception`](/en-US/docs/WebAssembly/JavaScript_interface/Exception) and throw that from a function called by WebAssembly.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/tag | data/mdn-content/files/en-us/webassembly/javascript_interface/tag/tag/index.md | ---
title: WebAssembly.Tag() constructor
slug: WebAssembly/JavaScript_interface/Tag/Tag
page-type: webassembly-constructor
browser-compat: webassembly.api.Tag.Tag
---
{{WebAssemblySidebar}}
The **`WebAssembly.Tag()`** constructor creates a new [`WebAssembly.Tag`](/en-US/docs/WebAssembly/JavaScript_interface/Tag) object.
## Syntax
```js-nolint
new WebAssembly.Tag(type)
```
### Parameters
- `type`
- : An object that can contain the following members:
- `parameters`
- : An array of [data types](/en-US/docs/WebAssembly/Understanding_the_text_format#types) (`"i32"`, `"i64"`, `"f32"`, `"f64"`, `"v128"`, `"externref"`, `"anyfunc"`).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if at least one of these conditions are met:
- The `type` parameter is not an object.
- The `type.parameters` property is not supplied.
- The `type.parameters` contains an unsupported data type.
## Examples
This creates a tag with two values.
```js
const tag = new WebAssembly.Tag({ parameters: ["i32", "i64"] });
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/tag | data/mdn-content/files/en-us/webassembly/javascript_interface/tag/type/index.md | ---
title: WebAssembly.Tag.prototype.type()
slug: WebAssembly/JavaScript_interface/Tag/type
page-type: webassembly-instance-method
browser-compat: webassembly.api.Tag.type
---
{{WebAssemblySidebar}}
The **`type()`** prototype method of the [`Tag`](/en-US/docs/WebAssembly/JavaScript_interface/Tag) object can be used to get the sequence of data types associated with the tag.
## Syntax
```js-nolint
type()
```
### Parameters
None
### Return value
An object with a property named `parameters` that references the array of data types associated with this [`Tag`](/en-US/docs/WebAssembly/JavaScript_interface/Tag).
This is a copy of the `type` object that was originally passed into the [`Tag()` constructor](/en-US/docs/WebAssembly/JavaScript_interface/Tag/Tag).
## Examples
This code snippet creates a tag defining two data types and then exports them using `type()`.
The result is printed to the console:
```js
const tag = new WebAssembly.Tag({ parameters: ["i32", "i64"] });
console.log(tag.type());
// Console output:
// Object { parameters: (2) [β¦] }
// parameters: Array [ "i32", "i64" ]
// <prototype>: Object { β¦ }
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/table/index.md | ---
title: WebAssembly.Table
slug: WebAssembly/JavaScript_interface/Table
page-type: webassembly-interface
browser-compat: webassembly.api.Table
---
{{WebAssemblySidebar}}
The **`WebAssembly.Table`** object is a JavaScript wrapper object β an array-like structure representing a WebAssembly table, which stores homogeneous references. A table created by JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript and WebAssembly.
> **Note:** Tables can currently only store function references, or host references, but this will likely be expanded in the future.
## Constructor
- [`WebAssembly.Table()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/Table)
- : Creates a new `Table` object.
## Instance properties
- [`Table.prototype.length`](/en-US/docs/WebAssembly/JavaScript_interface/Table/length) {{ReadOnlyInline}}
- : Returns the length of the table, i.e. the number of elements in the table.
## Instance methods
- [`Table.prototype.get()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/get)
- : Accessor function β gets the element stored at a given index.
- [`Table.prototype.grow()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/grow)
- : Increases the size of the `Table` instance by a specified number of elements.
- [`Table.prototype.set()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/set)
- : Sets an element stored at a given index to a given value.
## Examples
### Creating a new WebAssembly Table instance
The following example (see table2.html [source code](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/table2.html) and [live version](https://mdn.github.io/webassembly-examples/js-api-examples/table2.html)) creates a new WebAssembly Table instance with an initial size of 2 elements. We then print out the table length and contents of the two indexes (retrieved via [`Table.prototype.get()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/get) to show that the length is two and both elements are [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null).
```js
const tbl = new WebAssembly.Table({ initial: 2, element: "anyfunc" });
console.log(tbl.length); // "2"
console.log(tbl.get(0)); // "null"
console.log(tbl.get(1)); // "null"
```
We then create an import object that contains the table:
```js
const importObj = {
js: { tbl },
};
```
Finally, we load and instantiate a Wasm module (table2.wasm) using the [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) method. The table2.wasm module contains two functions (one that returns 42 and another that returns 83) and stores both into elements 0 and 1 of the imported table (see [text representation](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/table2.wat)). So after instantiation, the table still has length 2, but the elements now contain callable [Exported WebAssembly Functions](/en-US/docs/WebAssembly/Exported_functions) which we can call from JS.
```js
WebAssembly.instantiateStreaming(fetch("table2.wasm"), importObject).then(
(obj) => {
console.log(tbl.length);
console.log(tbl.get(0)());
console.log(tbl.get(1)());
},
);
```
Note how you've got to include a second function invocation operator at the end of the accessor to actually invoke the referenced function and log the value stored inside it (e.g. `get(0)()` rather than `get(0)`) .
This example shows that we're creating and accessing the table from JavaScript, but the same table is visible and callable inside the Wasm instance too.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/table | data/mdn-content/files/en-us/webassembly/javascript_interface/table/get/index.md | ---
title: WebAssembly.Table.prototype.get()
slug: WebAssembly/JavaScript_interface/Table/get
page-type: webassembly-instance-method
browser-compat: webassembly.api.Table.get
---
{{WebAssemblySidebar}}
The **`get()`** prototype method of the [`WebAssembly.Table()`](/en-US/docs/WebAssembly/JavaScript_interface/Table) object retrieves the element stored at a given index.
## Syntax
```js-nolint
get(index)
```
### Parameters
- `index`
- : The index of the element you want to retrieve.
### Return value
Depending the element type of the Table, can be a function reference β this is an [exported WebAssembly function](/en-US/docs/WebAssembly/Exported_functions), a JavaScript wrapper for an underlying Wasm function, or it can be a host reference.
### Exceptions
If _index_ is greater than or equal to [`Table.prototype.length`](/en-US/docs/WebAssembly/JavaScript_interface/Table/length), a {{jsxref("RangeError")}} is thrown.
## Examples
### Using get
The following example (see [table.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/table.html) on GitHub, and [view it live](https://mdn.github.io/webassembly-examples/js-api-examples/table.html) also) compiles and instantiates the loaded table.wasm byte code using the [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) method. It then retrieves the references stored in the exported table.
```js
WebAssembly.instantiateStreaming(fetch("table.wasm")).then((obj) => {
const tbl = obj.instance.exports.tbl;
console.log(tbl.get(0)()); // 13
console.log(tbl.get(1)()); // 42
});
```
Note how you've got to include a second function invocation operator at the end of the accessor to actually retrieve the value stored inside the reference (e.g. `get(0)()` rather than `get(0)`) β it is a function rather than a simple value.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/table | data/mdn-content/files/en-us/webassembly/javascript_interface/table/length/index.md | ---
title: WebAssembly.Table.prototype.length
slug: WebAssembly/JavaScript_interface/Table/length
page-type: webassembly-instance-property
browser-compat: webassembly.api.Table.length
---
{{WebAssemblySidebar}}
The read-only **`length`** prototype property of the [`WebAssembly.Table`](/en-US/docs/WebAssembly/JavaScript_interface/Table) object returns the length of the table, i.e. the number of elements in the table.
## Examples
### Using length
The following example creates a new WebAssembly Table instance with an initial size of
2 and a maximum size of 10:
```js
const table = new WebAssembly.Table({
element: "anyfunc",
initial: 2,
maximum: 10,
});
```
Grow the table by 1 using `WebAssembly.grow()`:
```js
console.log(table.length); // 2
table.grow(1);
console.log(table.length); // 3
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/table | data/mdn-content/files/en-us/webassembly/javascript_interface/table/set/index.md | ---
title: WebAssembly.Table.prototype.set()
slug: WebAssembly/JavaScript_interface/Table/set
page-type: webassembly-instance-method
browser-compat: webassembly.api.Table.set
---
{{WebAssemblySidebar}}
The **`set()`** prototype method of the [`WebAssembly.Table`](/en-US/docs/WebAssembly/JavaScript_interface/Table) object mutates a reference stored at a given index to a different value.
## Syntax
```js-nolint
set(index, value)
```
### Parameters
- `index`
- : The index of the function reference you want to mutate.
- `value`
- : The value you want to mutate the reference to. This must be a value of the table's element type. Depending on the type, it may be an [exported WebAssembly function](/en-US/docs/WebAssembly/Exported_functions), a JavaScript wrapper for an underlying Wasm function, or a host reference.
### Return value
None ({{jsxref("undefined")}}).
### Exceptions
- If `index` is greater than or equal to [`Table.prototype.length`](/en-US/docs/WebAssembly/JavaScript_interface/Table/length), a {{jsxref("RangeError")}} is thrown.
- If `value` is not of the element type of the table, a {{jsxref("TypeError")}} is thrown.
## Examples
### Using Table.set
The following example (see table2.html [source code](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/table2.html) and [live version](https://mdn.github.io/webassembly-examples/js-api-examples/table2.html)) creates a new WebAssembly Table instance with an initial size of two references. We then print out the table length and contents of the two indexes (retrieved via [`Table.prototype.get()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/get)) to show that the length is two, and the indexes currently contain no function references (they currently return [`null`](/en-US/docs/Web/JavaScript/Reference/Operators/null)).
```js
const tbl = new WebAssembly.Table({ initial: 2, element: "anyfunc" });
console.log(tbl.length);
console.log(tbl.get(0));
console.log(tbl.get(1));
```
We then create an import object that contains a reference to the table:
```js
const importObj = {
js: { tbl },
};
```
Finally, we load and instantiate a Wasm module (table2.wasm) using [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static), print the table length, and invoke the two referenced functions that are now stored in the table. The `table2.wasm` module adds two function references to the table, both of which print out a simple value (see [text representation](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/table2.wat):
```js
WebAssembly.instantiateStreaming(fetch("table2.wasm"), importObject).then(
(obj) => {
console.log(tbl.length);
console.log(tbl.get(0)());
console.log(tbl.get(1)());
},
);
```
Note how you've got to include a second function invocation operator at the end of the accessor to actually invoke the referenced function and log the value stored inside it (e.g. `get(0)()` rather than `get(0)`) .
This example shows that we're creating and accessing the table from JavaScript, but the same table is visible and callable inside the Wasm instance, too.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/table | data/mdn-content/files/en-us/webassembly/javascript_interface/table/table/index.md | ---
title: WebAssembly.Table() constructor
slug: WebAssembly/JavaScript_interface/Table/Table
page-type: webassembly-constructor
browser-compat: webassembly.api.Table.Table
---
{{WebAssemblySidebar}}
The **`WebAssembly.Table()`** constructor creates a new `Table` object of the given size and element type, filled with the provided value.
## Syntax
```js-nolint
new WebAssembly.Table(tableDescriptor)
new WebAssembly.Table(tableDescriptor, value)
```
### Parameters
- `tableDescriptor`
- : An object that can contain the following members:
- `element`
- : A string representing the type of value to be stored in the table. This can have a value of `"anyfunc"` (functions) or `"externref"` (host references).
- `initial`
- : The initial number of elements of the WebAssembly Table.
- `maximum` {{optional_inline}}
- : The maximum number of elements the WebAssembly Table is allowed to grow to.
- `value` {{optional_inline}}
- : The element to fill the newly-allocated space with.
### Exceptions
- If `tableDescriptor` is not an object, a {{jsxref("TypeError")}} is thrown.
- If `maximum` is specified and is smaller than `initial`, a {{jsxref("RangeError")}} is thrown.
- If `element` is not one of the [reference types](https://webassembly.github.io/spec/core/syntax/types.html#syntax-reftype), then a {{jsxref("TypeError")}} is thrown.
- If `value` is not a value of the type `element`, a {{jsxref("TypeError")}} is thrown.
## Examples
### Creating a new WebAssembly Table instance
The following example creates a `WebAssembly.Table` instance with an initial size of 2 elements. The `WebAssembly.Table` contents are populated using a WebAssembly module and are accessible from JavaScript. When viewing the [live example](https://mdn.github.io/webassembly-examples/js-api-examples/table2.html), open your developer console to display console log messages from the code snippets below.
This example uses the following reference files:
1. `table2.html`: An HTML file containing JavaScript that creates a `WebAssembly.Table` ([source code](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/table2.html))
2. `table2.wasm`: A WebAssembly module imported by the JavaScript code in `table2.html` ([source code](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/table2.wat))
In `table2.html`, we create a `WebAssembly.Table`:
```js
const tbl = new WebAssembly.Table({
initial: 2,
element: "anyfunc",
});
```
We can retrieve the index contents using [`Table.prototype.get()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/get):
```js
console.log(tbl.length); // a table with 2 elements
console.log(tbl.get(0)); // content for index 0 is null
console.log(tbl.get(1)); // content for index 1 is null
```
Next, we create an import object that contains the `WebAssembly.Table`:
```js
const importObject = {
js: { tbl },
};
```
Next, we load and instantiate a WebAssembly module. The `table2.wasm` module defines a table containing two functions. The first function returns 42, and the second returns 83:
```wasm
(module
(import "js" "tbl" (table 2 anyfunc))
(func $f42 (result i32) i32.const 42)
(func $f83 (result i32) i32.const 83)
(elem (i32.const 0) $f42 $f83)
)
```
We instantiate `table2.wasm` using the [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) method:
```js
const instantiating = WebAssembly.instantiateStreaming(
fetch("table2.wasm"),
importObject,
);
```
After instantiating `table2.wasm`, `tbl` is updated with the following:
- table length is still 2
- content for index 0 is now a function which returns 42
- content for index 1 is now a function which returns 83
The items at indexes 0 and 1 of the table are now callable [Exported WebAssembly Functions](/en-US/docs/WebAssembly/Exported_functions). To call them, note that we must add the function invocation operator `()` after the `get()` call:
```js
instantiating.then((obj) => {
console.log(tbl.length); // 2
console.log(tbl.get(0)()); // 42
console.log(tbl.get(1)()); // 83
});
```
While we are creating and accessing the `WebAssembly.Table` from JavaScript, the same `Table` is also visible and callable inside the WebAssembly instance.
### Creating a new WebAssembly Table instance with a value
The following example creates a new WebAssembly Table instance with 4 elements, full of the same object:
```js
const myObject = { hello: "world" };
const table = new WebAssembly.Table(
{
element: "externref",
initial: 4,
maximum: 4,
},
myObject,
);
console.log(myObject === table.get(2)); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/table | data/mdn-content/files/en-us/webassembly/javascript_interface/table/grow/index.md | ---
title: WebAssembly.Table.prototype.grow()
slug: WebAssembly/JavaScript_interface/Table/grow
page-type: webassembly-instance-method
browser-compat: webassembly.api.Table.grow
---
{{WebAssemblySidebar}}
The **`grow()`** prototype method of the [`WebAssembly.Table`](/en-US/docs/WebAssembly/JavaScript_interface/Table) object increases the size of the `Table` instance by a specified number of elements, filled with the provided value.
## Syntax
```js-nolint
grow(delta)
grow(delta, value)
```
### Parameters
- `delta`
- : The number of elements you want to grow the table by.
- `value` {{optional_inline}}
- : The element to fill the newly-allocated space with.
### Return value
The previous length of the table.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown in one of the following cases:
- If the current size added with `delta` exceeds the Table instance's maximum size capacity.
- If the client doesn't have enough memory for the allocation.
- {{jsxref("TypeError")}}
- : Thrown if `value` is not a value of the element type of the table.
## Examples
### Using grow
The following example creates a new WebAssembly Table instance with an initial size of
2 and a maximum size of 10:
```js
const table = new WebAssembly.Table({
element: "anyfunc",
initial: 2,
maximum: 10,
});
```
Grow the table by 1 element using `Table.grow()`:
```js
console.log(table.length); // 2
table.grow(1);
console.log(table.length); // 3
```
### Using grow with a value
The following example creates a new WebAssembly `Table` instance with an initial size of
0 and a maximum size of 4, filling it with an object:
```js
const myObject = { hello: "world" };
const table = new WebAssembly.Table({
element: "externref",
initial: 0,
maximum: 4,
});
```
Grow the table by 4 units and fill it with a value using `WebAssembly.grow()`:
```js
table.grow(4, myObject);
console.log(myObject === table.get(2)); // true
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/linkerror/index.md | ---
title: WebAssembly.LinkError
slug: WebAssembly/JavaScript_interface/LinkError
page-type: webassembly-interface
browser-compat: webassembly.api.LinkError
---
{{WebAssemblySidebar}}
The **`WebAssembly.LinkError`** object indicates an error during module instantiation (besides [traps](https://webassembly.github.io/simd/core/intro/overview.html#trap) from the start function).
## Constructor
- [`WebAssembly.LinkError()`](/en-US/docs/WebAssembly/JavaScript_interface/LinkError/LinkError)
- : Creates a new `WebAssembly.LinkError` object.
## Instance properties
- {{jsxref("Error.prototype.message", "WebAssembly.LinkError.prototype.message")}}
- : Error message. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.name", "WebAssembly.LinkError.prototype.name")}}
- : Error name. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.cause", "WebAssembly.LinkError.prototype.cause")}}
- : Error cause. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.fileName", "WebAssembly.LinkError.prototype.fileName")}} {{non-standard_inline}}
- : Path to file that raised this error. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.lineNumber", "WebAssembly.LinkError.prototype.lineNumber")}} {{non-standard_inline}}
- : Line number in file that raised this error. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.columnNumber", "WebAssembly.LinkError.prototype.columnNumber")}} {{non-standard_inline}}
- : Column number in line that raised this error. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.stack", "WebAssembly.LinkError.prototype.stack")}} {{non-standard_inline}}
- : Stack trace. Inherited from {{jsxref("Error")}}.
## Instance methods
- {{jsxref("Error.prototype.toString", "WebAssembly.LinkError.prototype.toString()")}}
- : Returns a string representing the specified `Error` object. Inherited from {{jsxref("Error")}}.
## Examples
### Creating a new LinkError instance
The following snippet creates a new `LinkError` instance, and logs its details to the console:
```js
try {
throw new WebAssembly.LinkError("Hello", "someFile", 10);
} catch (e) {
console.log(e instanceof LinkError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "LinkError"
console.log(e.fileName); // "someFile"
console.log(e.lineNumber); // 10
console.log(e.columnNumber); // 0
console.log(e.stack); // returns the location where the code was run
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/linkerror | data/mdn-content/files/en-us/webassembly/javascript_interface/linkerror/linkerror/index.md | ---
title: WebAssembly.LinkError() constructor
slug: WebAssembly/JavaScript_interface/LinkError/LinkError
page-type: webassembly-constructor
browser-compat: webassembly.api.LinkError.LinkError
---
{{WebAssemblySidebar}}
The **`WebAssembly.LinkError()`** constructor creates a new
WebAssembly `LinkError` object, which indicates an error during module
instantiation (besides [traps](https://webassembly.github.io/simd/core/intro/overview.html#trap)
from the start function).
## Syntax
```js-nolint
new WebAssembly.LinkError()
new WebAssembly.LinkError(message)
new WebAssembly.LinkError(message, options)
new WebAssembly.LinkError(message, fileName)
new WebAssembly.LinkError(message, fileName, lineNumber)
```
### Parameters
- `message` {{optional_inline}}
- : Human-readable description of the error.
- `options` {{optional_inline}}
- : An object that has the following properties:
- `cause` {{optional_inline}}
- : A property indicating the specific cause of the error.
When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.
- `fileName` {{optional_inline}} {{non-standard_inline}}
- : The name of the file containing the code that caused the exception.
- `lineNumber` {{optional_inline}} {{non-standard_inline}}
- : The line number of the code that caused the exception.
## Examples
### Creating a new LinkError instance
The following snippet creates a new `LinkError` instance, and logs its
details to the console:
```js
try {
throw new WebAssembly.LinkError("Hello", "someFile", 10);
} catch (e) {
console.log(e instanceof LinkError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "LinkError"
console.log(e.fileName); // "someFile"
console.log(e.lineNumber); // 10
console.log(e.columnNumber); // 0
console.log(e.stack); // returns the location where the code was run
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/compile_static/index.md | ---
title: WebAssembly.compile()
slug: WebAssembly/JavaScript_interface/compile_static
page-type: webassembly-function
browser-compat: webassembly.api.compile_static
---
{{WebAssemblySidebar}}
The **`WebAssembly.compile()`** static method compiles WebAssembly binary code into a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object.
This function is useful if it is necessary to compile a module before it can be instantiated (otherwise, the [`WebAssembly.instantiate()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static) function should be used).
> **Note:** Webpages that have strict [Content Security Policy (CSP)](/en-US/docs/Web/HTTP/CSP) might block WebAssembly from compiling and executing modules.
> For more information on allowing WebAssembly compilation and execution, see the [script-src CSP](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src).
## Syntax
```js-nolint
WebAssembly.compile(bufferSource)
```
### Parameters
- `bufferSource`
- : A [typed array](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) or {{jsxref("ArrayBuffer")}}
containing the binary code of the Wasm module you want to compile.
### Return value
A `Promise` that resolves to a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object
representing the compiled module.
### Exceptions
- If `bufferSource` is not a [typed array](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) or {{jsxref("ArrayBuffer")}},
the promise rejects with a {{jsxref("TypeError")}}.
- If compilation fails, the promise rejects with a
[`WebAssembly.CompileError`](/en-US/docs/WebAssembly/JavaScript_interface/CompileError).
## Examples
### Using compile
The following example compiles the loaded simple.wasm byte code using the
`compile()` function and then sends it to a [worker](/en-US/docs/Web/API/Web_Workers_API) using [postMessage()](/en-US/docs/Web/API/Worker/postMessage).
```js
const worker = new Worker("wasm_worker.js");
fetch("simple.wasm")
.then((response) => response.arrayBuffer())
.then((bytes) => WebAssembly.compile(bytes))
.then((mod) => worker.postMessage(mod));
```
> **Note:** You'll probably want to use
> [`WebAssembly.compileStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/compileStreaming_static) in most cases, as it is more efficient
> than `compile()`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/instantiatestreaming_static/index.md | ---
title: WebAssembly.instantiateStreaming()
slug: WebAssembly/JavaScript_interface/instantiateStreaming_static
page-type: webassembly-function
browser-compat: webassembly.api.instantiateStreaming_static
---
{{WebAssemblySidebar}}
The **`WebAssembly.instantiateStreaming()`** static method compiles
and instantiates a WebAssembly module directly from a streamed underlying source. This
is the most efficient, optimized way to load Wasm code.
> **Note:** Webpages that have strict [Content Security Policy (CSP)](/en-US/docs/Web/HTTP/CSP) might block WebAssembly from compiling and executing modules.
> For more information on allowing WebAssembly compilation and execution, see the [script-src CSP](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src).
## Syntax
```js-nolint
WebAssembly.instantiateStreaming(source, importObject)
```
### Parameters
- `source`
- : A [`Response`](/en-US/docs/Web/API/Response)
object or a promise that will fulfill with one, representing the underlying source of
a Wasm module you want to stream, compile, and instantiate.
- `importObject` {{optional_inline}}
- : An object containing the values to be imported into the newly-created
`Instance`, such as functions or [`WebAssembly.Memory`](/en-US/docs/WebAssembly/JavaScript_interface/Memory) objects.
There must be one matching property for each declared import of the compiled module or
else a
[`WebAssembly.LinkError`](/en-US/docs/WebAssembly/JavaScript_interface/LinkError)
is thrown.
### Return value
A `Promise` that resolves to a `ResultObject` which contains two
fields:
- `module`: A [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object representing the
compiled WebAssembly module. This `Module` can be instantiated again or
shared via [postMessage()](/en-US/docs/Web/API/Worker/postMessage).
- `instance`: A [`WebAssembly.Instance`](/en-US/docs/WebAssembly/JavaScript_interface/Instance) object that contains all
the [Exported WebAssembly functions](/en-US/docs/WebAssembly/Exported_functions).
### Exceptions
- If either of the parameters are not of the correct type or structure, a
{{jsxref("TypeError")}} is thrown.
- If the operation fails, the promise rejects with a
[`WebAssembly.CompileError`](/en-US/docs/WebAssembly/JavaScript_interface/CompileError), [`WebAssembly.LinkError`](/en-US/docs/WebAssembly/JavaScript_interface/LinkError), or
[`WebAssembly.RuntimeError`](/en-US/docs/WebAssembly/JavaScript_interface/RuntimeError), depending on the cause of the failure.
## Examples
### Instantiating streaming
The following example (see our [instantiate-streaming.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/instantiate-streaming.html)
demo on GitHub, and [view it live](https://mdn.github.io/webassembly-examples/js-api-examples/instantiate-streaming.html) also)
directly streams a Wasm module from an underlying source then
compiles and instantiates it, the promise fulfilling with a `ResultObject`.
Because the `instantiateStreaming()` function accepts a promise for a [`Response`](/en-US/docs/Web/API/Response)
object, you can directly pass it a [`fetch()`](/en-US/docs/Web/API/fetch)
call, and it will pass the response into the function when it fulfills.
```js
const importObject = { imports: { imported_func: (arg) => console.log(arg) } };
WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
(obj) => obj.instance.exports.exported_func(),
);
```
The `ResultObject`'s instance member is then accessed, and the contained
exported function invoked.
> **Note:** For this to work, `.wasm` files should be returned
> with an `application/wasm` MIME type by the server.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/validate_static/index.md | ---
title: WebAssembly.validate()
slug: WebAssembly/JavaScript_interface/validate_static
page-type: webassembly-function
browser-compat: webassembly.api.validate_static
---
{{WebAssemblySidebar}}
The **`WebAssembly.validate()`** static method validates a given [typed array](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) of WebAssembly binary
code, returning whether the bytes form a valid Wasm module (`true`) or not
(`false`).
## Syntax
```js-nolint
WebAssembly.validate(bufferSource)
```
### Parameters
- `bufferSource`
- : A [typed array](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) or [ArrayBuffer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
containing WebAssembly binary code to be validated.
### Return value
A boolean that specifies whether `bufferSource` is valid Wasm code
(`true`) or not (`false`).
### Exceptions
If `bufferSource` is not a [typed array](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) or [ArrayBuffer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer),
a {{jsxref("TypeError")}} is thrown.
## Examples
### Using validate
The following example (see the validate.html [source code](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/validate.html),
and [see it live too](https://mdn.github.io/webassembly-examples/js-api-examples/validate.html))
fetches a Wasm module and converts it into a typed array.
The `validate()` method is then used to check whether the module is valid.
```js
fetch("simple.wasm")
.then((response) => response.arrayBuffer())
.then((bytes) => {
const valid = WebAssembly.validate(bytes);
console.log(
`The given bytes are ${valid ? "" : "not "}a valid Wasm module`,
);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/instantiate_static/index.md | ---
title: WebAssembly.instantiate()
slug: WebAssembly/JavaScript_interface/instantiate_static
page-type: webassembly-function
browser-compat: webassembly.api.instantiate_static
---
{{WebAssemblySidebar}}
The **`WebAssembly.instantiate()`** function allows you to
compile and instantiate WebAssembly code. This function has two overloads:
- The primary overload takes the WebAssembly binary code, in the form of a [typed array](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) or
{{jsxref("ArrayBuffer")}}, and performs both compilation and instantiation in one
step. The returned `Promise` resolves to both a compiled
[`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) and its first [`WebAssembly.Instance`](/en-US/docs/WebAssembly/JavaScript_interface/Instance).
- The secondary overload takes an already-compiled [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module)
and returns a `Promise` that resolves to an `Instance` of that
`Module`. This overload is useful if the `Module` has already
been compiled.
> **Warning:** This method is not the most efficient way of fetching and
> instantiating Wasm modules. If at all possible, you should use the newer
> [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) method instead, which fetches,
> compiles, and instantiates a module all in one step, directly from the raw bytecode,
> so doesn't require conversion to an {{jsxref("ArrayBuffer")}}.
## Syntax
### Primary overload β taking Wasm binary code
```js
WebAssembly.instantiate(bufferSource, importObject);
```
#### Parameters
- `bufferSource`
- : A [typed array](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) or
{{jsxref("ArrayBuffer")}} containing the binary code of the Wasm module you want to
compile, or a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module).
- `importObject` {{optional_inline}}
- : An object containing the values to be imported into the newly-created
`Instance`, such as functions or [`WebAssembly.Memory`](/en-US/docs/WebAssembly/JavaScript_interface/Memory) objects.
There must be one matching property for each declared import of the compiled module or
else a [`WebAssembly.LinkError`](/en-US/docs/WebAssembly/JavaScript_interface/LinkError) is thrown.
#### Return value
A `Promise` that resolves to a `ResultObject` which contains two
fields:
- `module`: A [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object representing the compiled WebAssembly module. This `Module` can be instantiated again, shared via {{domxref("Worker.postMessage", "postMessage()")}}, or [cached](/en-US/docs/WebAssembly/Caching_modules).
- `instance`: A [`WebAssembly.Instance`](/en-US/docs/WebAssembly/JavaScript_interface/Instance) object that contains all the [Exported WebAssembly functions](/en-US/docs/WebAssembly/Exported_functions).
#### Exceptions
- If either of the parameters are not of the correct type or structure,
the promise rejects with a {{jsxref("TypeError")}}.
- If the operation fails, the promise rejects with a
[`WebAssembly.CompileError`](/en-US/docs/WebAssembly/JavaScript_interface/CompileError), [`WebAssembly.LinkError`](/en-US/docs/WebAssembly/JavaScript_interface/LinkError), or
[`WebAssembly.RuntimeError`](/en-US/docs/WebAssembly/JavaScript_interface/RuntimeError), depending on the cause of the failure.
### Secondary overload β taking a module object instance
```js
WebAssembly.instantiate(module, importObject);
```
#### Parameters
- `module`
- : The [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object to be instantiated.
- `importObject` {{optional_inline}}
- : An object containing the values to be imported into the newly-created
`Instance`, such as functions or [`WebAssembly.Memory`](/en-US/docs/WebAssembly/JavaScript_interface/Memory) objects.
There must be one matching property for each declared import of `module` or
else a [`WebAssembly.LinkError`](/en-US/docs/WebAssembly/JavaScript_interface/LinkError) is thrown.
#### Return value
A `Promise` that resolves to an [`WebAssembly.Instance`](/en-US/docs/WebAssembly/JavaScript_interface/Instance) object.
#### Exceptions
- If either of the parameters are not of the correct type or structure, a
{{jsxref("TypeError")}} is thrown.
- If the operation fails, the promise rejects with a
[`WebAssembly.CompileError`](/en-US/docs/WebAssembly/JavaScript_interface/CompileError), [`WebAssembly.LinkError`](/en-US/docs/WebAssembly/JavaScript_interface/LinkError), or
[`WebAssembly.RuntimeError`](/en-US/docs/WebAssembly/JavaScript_interface/RuntimeError), depending on the cause of the failure.
## Examples
> **Note:** You'll probably want to use [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) in most cases, as it is more efficient than `instantiate()`.
### First overload example
After fetching some WebAssembly bytecode using fetch, we compile and instantiate the
module using the `WebAssembly.instantiate()` function, importing a
JavaScript function into the WebAssembly Module in the process. We then call an [Exported WebAssembly function](/en-US/docs/WebAssembly/Exported_functions)
that is exported by the `Instance`.
```js
const importObject = {
imports: {
imported_func(arg) {
console.log(arg);
},
},
};
fetch("simple.wasm")
.then((response) => response.arrayBuffer())
.then((bytes) => WebAssembly.instantiate(bytes, importObject))
.then((result) => result.instance.exports.exported_func());
```
> **Note:** You can also find this example at [index.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/index.html)
> on GitHub ([view it live also](https://mdn.github.io/webassembly-examples/js-api-examples/)).
### Second overload example
The following example (see our [index-compile.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/index-compile.html)
demo on GitHub, and [view it live](https://mdn.github.io/webassembly-examples/js-api-examples/index-compile.html) also)
compiles the loaded simple.wasm byte code using the
[`WebAssembly.compileStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/compileStreaming_static) method and then sends it to a [worker](/en-US/docs/Web/API/Web_Workers_API) using
{{domxref("Worker.postMessage", "postMessage()")}}.
```js
const worker = new Worker("wasm_worker.js");
WebAssembly.compileStreaming(fetch("simple.wasm")).then((mod) =>
worker.postMessage(mod),
);
```
In the worker (see
[`wasm_worker.js`](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/wasm_worker.js))
we define an import object for the module to use, then set up an event handler to
receive the module from the main thread. When the module is received, we create an
instance from it using the `WebAssembly.instantiate()` method and invoke an
exported function from inside it.
```js
const importObject = {
imports: {
imported_func(arg) {
console.log(arg);
},
},
};
onmessage = (e) => {
console.log("module received from main thread");
const mod = e.data;
WebAssembly.instantiate(mod, importObject).then((instance) => {
instance.exports.exported_func();
});
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/global/index.md | ---
title: WebAssembly.Global
slug: WebAssembly/JavaScript_interface/Global
page-type: webassembly-interface
browser-compat: webassembly.api.Global
---
{{WebAssemblySidebar}}
A **`WebAssembly.Global`** object represents a global variable instance, accessible from both JavaScript and importable/exportable across one or more [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) instances. This allows dynamic linking of multiple modules.
## Constructor
- [`WebAssembly.Global()`](/en-US/docs/WebAssembly/JavaScript_interface/Global/Global)
- : Creates a new `Global` object.
## Global instances
All `Global` instances inherit from the `Global()` constructor's prototype object β this can be modified to affect all `Global` instances.
### Instance properties
- `Global.prototype.constructor`
- : Returns the function that created this object's instance. By default this is the [`WebAssembly.Global()`](/en-US/docs/WebAssembly/JavaScript_interface/Global/Global) constructor.
- `Global.prototype[@@toStringTag]`
- : The initial value of the [@@toStringTag](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the String value "WebAssembly.Global".
- `Global.prototype.value`
- : The value contained inside the global variable β this can be used to directly set and get the global's value.
### Instance methods
- `Global.prototype.valueOf()`
- : Old-style method that returns the value contained inside the global variable.
## Examples
### Creating a new Global instance
The following example shows a new global instance being created using the `WebAssembly.Global()` constructor. It is being defined as a mutable `i32` type, with a value of 0.
The value of the global is then changed, first to `42` using the `Global.value` property, and then to 43 using the `incGlobal()` function exported out of the `global.wasm` module (this adds 1 to whatever value is given to it and then returns the new value).
```js
const output = document.getElementById("output");
function assertEq(msg, got, expected) {
const result =
got === expected
? `SUCCESS! Got: ${got}<br>`
: `FAIL!<br>Got: ${got}<br>Expected: ${expected}<br>`;
output.innerHTML += `Testing ${msg}: ${result}`;
}
assertEq("WebAssembly.Global exists", typeof WebAssembly.Global, "function");
const global = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
WebAssembly.instantiateStreaming(fetch("global.wasm"), { js: { global } }).then(
({ instance }) => {
assertEq(
"getting initial value from wasm",
instance.exports.getGlobal(),
0,
);
global.value = 42;
assertEq(
"getting JS-updated value from wasm",
instance.exports.getGlobal(),
42,
);
instance.exports.incGlobal();
assertEq("getting wasm-updated value from JS", global.value, 43);
},
);
```
> **Note:** You can see the example [running live on GitHub](https://mdn.github.io/webassembly-examples/js-api-examples/global.html); see also the [source code](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/global.html).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
- [Import/Export mutable globals proposal](https://github.com/WebAssembly/mutable-global/blob/master/proposals/mutable-global/Overview.md)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/global | data/mdn-content/files/en-us/webassembly/javascript_interface/global/global/index.md | ---
title: WebAssembly.Global() constructor
slug: WebAssembly/JavaScript_interface/Global/Global
page-type: webassembly-constructor
browser-compat: webassembly.api.Global.Global
---
{{WebAssemblySidebar}}
A **`WebAssembly.Global()`** constructor creates a new `Global` object representing a global variable instance, accessible from both JavaScript and importable/exportable across one or more [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) instances.
This allows dynamic linking of multiple modules.
## Syntax
```js-nolint
new WebAssembly.Global(descriptor, value)
```
### Parameters
- `descriptor`
- : An object, which contains two properties:
- `value`: A string representing the
data type of the global. This can be any one of:
- `i32`: A 32-bit integer.
- `i64`: A 64-bit integer. (In JavaScript, this is represented as a {{jsxref("BigInt")}})
- `f32`: A 32-bit floating point number.
- `f64`: A 64-bit floating point number.
- `v128`: A 128-bit vector.
- `externref`: A host reference.
- `anyfunc`: A function reference.
- `mutable`: A boolean value that determines whether the global is
mutable or not. By default, this is `false`.
- `value`
- : The value the variable contains. This can be any value, as long as its type matches the variable's data type.
If no value is specified, a typed 0 value is used where the value of `descriptor.value` is one of `i32`, `i64`, `f32`, or `f64`, and `null` is used if `descriptor.value` is `externref` or `anyfunc` (as specified by the [`DefaultValue` algorithm](https://webassembly.github.io/spec/js-api/#defaultvalue)).
## Examples
### Creating a new Global instance
The following example shows a new global instance being created using the `WebAssembly.Global()` constructor.
It is being defined as a mutable `i32` type, with a value of 0.
The value of the global is then changed, first to `42` using the `Global.value` property, and then to 43 using the `incGlobal()` function exported out of the `global.wasm` module (this adds 1 to whatever value is given to it and then returns the new value).
```js
const output = document.getElementById("output");
function assertEq(msg, got, expected) {
const result =
got === expected
? `SUCCESS! Got: ${got}<br>`
: `FAIL!<br>Got: ${got}<br>Expected: ${expected}<br>`;
output.innerHTML += `Testing ${msg}: ${result}`;
}
assertEq("WebAssembly.Global exists", typeof WebAssembly.Global, "function");
const global = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
WebAssembly.instantiateStreaming(fetch("global.wasm"), { js: { global } }).then(
({ instance }) => {
assertEq(
"getting initial value from wasm",
instance.exports.getGlobal(),
0,
);
global.value = 42;
assertEq(
"getting JS-updated value from wasm",
instance.exports.getGlobal(),
42,
);
instance.exports.incGlobal();
assertEq("getting wasm-updated value from JS", global.value, 43);
},
);
```
> **Note:** You can see the example [running live on GitHub](https://mdn.github.io/webassembly-examples/js-api-examples/global.html);
> see also the [source code](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/global.html).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
- [Import/Export mutable globals proposal](https://github.com/WebAssembly/mutable-global/blob/master/proposals/mutable-global/Overview.md)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/memory/index.md | ---
title: WebAssembly.Memory
slug: WebAssembly/JavaScript_interface/Memory
page-type: webassembly-interface
browser-compat: webassembly.api.Memory
---
{{WebAssemblySidebar}}
The **`WebAssembly.Memory`** object is a resizable {{jsxref("ArrayBuffer")}} or {{jsxref("SharedArrayBuffer")}} that holds the raw bytes of memory accessed by a [`WebAssembly.Instance`](/en-US/docs/WebAssembly/JavaScript_interface/Instance).
Both WebAssembly and JavaScript can create `Memory` objects. If you want to access the memory created in JS from Wasm or vice versa, you can pass a reference to the memory from one side to the other.
## Constructor
- [`WebAssembly.Memory()`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/Memory)
- : Creates a new `Memory` object.
## Instance properties
- [`Memory.prototype.buffer`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/buffer) {{ReadOnlyInline}}
- : Returns the buffer contained in the memory.
## Instance methods
- [`Memory.prototype.grow()`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/grow)
- : Increases the size of the memory instance by a specified number of WebAssembly pages (each one is 64KiB in size). Detaches the previous `buffer`.
## Examples
### Creating a new Memory object
There are two ways to get a `WebAssembly.Memory` object. The first way is to construct it from JavaScript. The following snippet creates a new WebAssembly Memory instance with an initial size of 10 pages (640KiB), and a maximum size of 100 pages (6.4MiB). Its [`buffer`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/buffer) property will return an {{jsxref("ArrayBuffer")}}.
```js
const memory = new WebAssembly.Memory({
initial: 10,
maximum: 100,
});
```
The following example (see [memory.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/memory.html) on GitHub, and [view it live also](https://mdn.github.io/webassembly-examples/js-api-examples/memory.html)) fetches and instantiates the loaded memory.wasm bytecode using the [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) function, while importing the memory created in the line above. It then stores some values in that memory, exports a function, and uses the exported function to sum those values.
```js
const memory = new WebAssembly.Memory({
initial: 10,
maximum: 100,
});
WebAssembly.instantiateStreaming(fetch("memory.wasm"), {
js: { mem: memory },
}).then((obj) => {
const summands = new Uint32Array(memory.buffer);
for (let i = 0; i < 10; i++) {
summands[i] = i;
}
const sum = obj.instance.exports.accumulate(0, 10);
console.log(sum);
});
```
Another way to get a `WebAssembly.Memory` object is to have it exported by a WebAssembly module. This memory can be accessed in the `exports` property of the WebAssembly instance (after the memory is exported within the WebAssembly module). The following example imports a memory exported from WebAssembly with the name `memory`, and then prints out the first element of the memory, interpreted as an {{jsxref("Uint32Array")}}.
```js
WebAssembly.instantiateStreaming(fetch("memory.wasm")).then((obj) => {
const values = new Uint32Array(obj.instance.exports.memory.buffer);
console.log(values[0]);
});
```
### Creating a shared memory
By default, WebAssembly memories are unshared. You can create a [shared memory](/en-US/docs/WebAssembly/Understanding_the_text_format#shared_memories) from JavaScript by passing `shared: true` in the constructor's initialization object:
```js
const memory = new WebAssembly.Memory({
initial: 10,
maximum: 100,
shared: true,
});
```
This memory's `buffer` property will return a {{jsxref("SharedArrayBuffer")}}.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/memory | data/mdn-content/files/en-us/webassembly/javascript_interface/memory/buffer/index.md | ---
title: WebAssembly.Memory.prototype.buffer
slug: WebAssembly/JavaScript_interface/Memory/buffer
page-type: webassembly-instance-property
browser-compat: webassembly.api.Memory.buffer
---
{{WebAssemblySidebar}}
The read-only **`buffer`** prototype property of the [`WebAssembly.Memory`](/en-US/docs/WebAssembly/JavaScript_interface/Memory) object returns the buffer contained in the memory. Depending on whether or not the memory was constructed with `shared: true`, the buffer is either an {{jsxref("ArrayBuffer")}} or a {{jsxref("SharedArrayBuffer")}}.
## Examples
### Using buffer
The following example (see [memory.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/memory.html) on GitHub, and [view it live also](https://mdn.github.io/webassembly-examples/js-api-examples/memory.html)) fetches and instantiates the loaded memory.wasm bytecode using the [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) function, while importing the memory created in the line above. It then stores some values in that memory, exports a function, and uses the exported function to sum those values.
```js
const memory = new WebAssembly.Memory({
initial: 10,
maximum: 100,
});
WebAssembly.instantiateStreaming(fetch("memory.wasm"), {
js: { mem: memory },
}).then((obj) => {
const summands = new Uint32Array(memory.buffer);
for (let i = 0; i < 10; i++) {
summands[i] = i;
}
const sum = obj.instance.exports.accumulate(0, 10);
console.log(sum);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/memory | data/mdn-content/files/en-us/webassembly/javascript_interface/memory/grow/index.md | ---
title: WebAssembly.Memory.prototype.grow()
slug: WebAssembly/JavaScript_interface/Memory/grow
page-type: webassembly-instance-method
browser-compat: webassembly.api.Memory.grow
---
{{WebAssemblySidebar}}
The **`grow()`** prototype method of the [`WebAssembly.Memory`](/en-US/docs/WebAssembly/JavaScript_interface/Memory) object increases the size of the memory instance by a specified number of WebAssembly pages.
## Syntax
```js-nolint
grow(delta)
```
### Parameters
- `delta`
- : The number of WebAssembly pages you want to grow the memory by (each one is 64KiB in size).
### Return value
The previous size of the memory, in units of WebAssembly pages.
### Exceptions
- {{jsxref("RangeError")}}: If the current size added with `delta` exceeds the Memory instance's maximum size capacity.
## Examples
### Using grow
The following example creates a new WebAssembly Memory instance with an initial size of 1 page (64KiB), and a maximum size of 10 pages (640KiB).
```js
const memory = new WebAssembly.Memory({
initial: 1,
maximum: 10,
});
```
We can then grow the instance by one page like so:
```js
const bytesPerPage = 64 * 1024;
console.log(memory.buffer.byteLength / bytesPerPage); // "1"
console.log(memory.grow(1)); // "1"
console.log(memory.buffer.byteLength / bytesPerPage); // "2"
```
Note the return value of `grow()` here is the previous number of WebAssembly pages.
### Detachment upon growing
Every call to `grow` will detach any references to the old `buffer`, even for `grow(0)`!
Detachment means that the {{jsxref("ArrayBuffer")}}'s `byteLength` becomes zero, and it no longer has bytes accessible to JavaScript.
Accessing the `buffer` property after calling `grow`, will yield an `ArrayBuffer` with the correct length.
```js example-bad
const memory = new WebAssembly.Memory({
initial: 1,
});
const oldMemoryView = new Uint8Array(memory.buffer);
memory.grow(1);
// the array is empty!
console.log(oldMemoryView); // Uint8Array []
```
```js example-good
const memory = new WebAssembly.Memory({
initial: 1,
});
memory.grow(1);
const currentMemoryView = new Uint8Array(memory.buffer);
// the array is full of zeros
console.log(currentMemoryView); // Uint8Array(131072) [ 0, 0, 0, ... ]
// 131072 = 64KiB * 2
```
For a shared `Memory` instance, the initial `buffer` (which would be a [`SharedArrayBuffer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) in such case) will not become detached, but rather its length will not be updated. Accesses to the `buffer` property after growing will yield a larger `SharedArrayBuffer` which may access a larger span of memory than the buffer from before growing the `Memory`. Every `SharedArrayBuffer` from the `buffer` property will all refer to the start of the same memory address range, and thus manipulate the same data.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/memory | data/mdn-content/files/en-us/webassembly/javascript_interface/memory/memory/index.md | ---
title: WebAssembly.Memory() constructor
slug: WebAssembly/JavaScript_interface/Memory/Memory
page-type: webassembly-constructor
browser-compat: webassembly.api.Memory.Memory
---
{{WebAssemblySidebar}}
The **`WebAssembly.Memory()`** constructor creates a new `Memory` object whose [`buffer`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/buffer) property is a resizable {{jsxref("ArrayBuffer")}} or {{jsxref("SharedArrayBuffer")}} that holds the raw bytes of memory accessed by a [`WebAssembly.Instance`](/en-US/docs/WebAssembly/JavaScript_interface/Instance).
A memory object created by JavaScript or in WebAssembly code will be accessible and mutable from both JavaScript and WebAssembly, provided that the code constructed the object, or has been given the object.
Both WebAssembly and JavaScript can create `Memory` objects. If you want to access the memory created in JS from Wasm or vice versa, you can pass a reference to the memory from one side to the other.
## Syntax
```js-nolint
new WebAssembly.Memory(memoryDescriptor)
```
### Parameters
- `memoryDescriptor`
- : An object that can contain the following members:
- `initial`
- : The initial size of the WebAssembly Memory, in units of WebAssembly pages.
- `maximum` {{optional_inline}}
- : The maximum size the WebAssembly Memory is allowed to grow to, in units of
WebAssembly pages. When present, the `maximum` parameter acts as a hint
to the engine to reserve memory up front. However, the engine may ignore or clamp
this reservation request. Unshared WebAssembly memories don't need to set a
`maximum`, but shared memories do.
- `shared` {{optional_inline}}
- : A boolean value that defines whether the memory is a shared memory or not. If
set to `true`, it is a shared memory. The default is `false`.
> **Note:** A WebAssembly page has a constant size of 65,536 bytes, i.e., 64KiB.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if at least one of these conditions is met:
- `memoryDescriptor` is not an object.
- `initial` is not specified.
- `shared` is present and `true`, yet `maximum` is not specified.
- {{jsxref("RangeError")}}
- : Thrown if at least one of these conditions is met:
- `maximum` is specified and is smaller than `initial`.
- `initial` exceeds 65,536 (2^16). 2^16 pages is 2^16 \* 64KiB = 4GiB bytes, which is the maximum range that a Wasm module can address, as Wasm currently only allows 32-bit addressing.
- Allocation fails. This may occur due to attempting to allocate too much at once, or if the User Agent is otherwise out of memory.
## Examples
### Creating a new Memory instance
There are two ways to get a `WebAssembly.Memory` object: construct it from JavaScript, or have it exported by a WebAssembly module.
The following example (see [memory.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/memory.html) on GitHub, and [view it live also](https://mdn.github.io/webassembly-examples/js-api-examples/memory.html)) creates a new WebAssembly Memory instance with an initial size of 10 pages (640KiB), and a maximum size of 100 pages (6.4MiB). The example fetches and instantiates the loaded memory.wasm bytecode using the [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) function, while importing the memory created in the line above. It then stores some values in that memory, exports a function, and uses the exported function to sum those values. The `Memory` object's [`buffer`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/buffer) property will return an {{jsxref("ArrayBuffer")}}.
```js
const memory = new WebAssembly.Memory({
initial: 10,
maximum: 100,
});
WebAssembly.instantiateStreaming(fetch("memory.wasm"), {
js: { mem: memory },
}).then((obj) => {
const summands = new Uint32Array(memory.buffer);
for (let i = 0; i < 10; i++) {
summands[i] = i;
}
const sum = obj.instance.exports.accumulate(0, 10);
console.log(sum);
});
```
### Creating a shared memory
By default, WebAssembly memories are unshared.
You can create a [shared memory](/en-US/docs/WebAssembly/Understanding_the_text_format#shared_memories)
from JavaScript by passing `shared: true` in the constructor's initialization object:
```js
const memory = new WebAssembly.Memory({
initial: 10,
maximum: 100,
shared: true,
});
```
This memory's `buffer` property will return a {{jsxref("SharedArrayBuffer")}}.
## Specifications
The `shared` attribute is only documented in [the Threading proposal for WebAssembly](https://github.com/WebAssembly/threads/blob/master/proposals/threads/Overview.md#javascript-api-changes) and not part of the official specs.
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/module/index.md | ---
title: WebAssembly.Module
slug: WebAssembly/JavaScript_interface/Module
page-type: webassembly-interface
browser-compat: webassembly.api.Module
---
{{WebAssemblySidebar}}
A **`WebAssembly.Module`** object contains stateless WebAssembly code that has already been compiled by the browser β this can be efficiently [shared with Workers](/en-US/docs/Web/API/Worker/postMessage), and instantiated multiple times.
## Constructor
- [`WebAssembly.Module()`](/en-US/docs/WebAssembly/JavaScript_interface/Module/Module)
- : Creates a new `Module` object.
## Static methods
- [`WebAssembly.Module.customSections()`](/en-US/docs/WebAssembly/JavaScript_interface/Module/customSections_static)
- : Given a `Module` and string, returns a copy of the contents of all custom sections in the module with the given string name.
- [`WebAssembly.Module.exports()`](/en-US/docs/WebAssembly/JavaScript_interface/Module/exports_static)
- : Given a `Module`, returns an array containing descriptions of all the declared exports.
- [`WebAssembly.Module.imports()`](/en-US/docs/WebAssembly/JavaScript_interface/Module/imports_static)
- : Given a `Module`, returns an array containing descriptions of all the declared imports.
## Examples
### Sending a compiled module to a worker
The following example compiles the loaded `simple.wasm` byte code using the [`WebAssembly.compileStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/compileStreaming_static) method and sends the resulting `Module` instance to a [worker](/en-US/docs/Web/API/Web_Workers_API) using {{domxref("Worker/postMessage", "postMessage()")}}.
See the `index-compile.html` [source code](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/index-compile.html) or [view it live](https://mdn.github.io/webassembly-examples/js-api-examples/index-compile.html).
```js
const worker = new Worker("wasm_worker.js");
WebAssembly.compileStreaming(fetch("simple.wasm")).then((mod) =>
worker.postMessage(mod),
);
```
The worker function [`wasm_worker.js`](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/wasm_worker.js) defines an import object for the module to use. The function then sets up an event handler to receive the module from the main thread. When the module is received, we create an instance from it using the [`WebAssembly.instantiate()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static) method and invoke an exported function from inside it.
```js
const importObject = {
imports: {
imported_func(arg) {
console.log(arg);
},
},
};
onmessage = (e) => {
console.log("module received from main thread");
const mod = e.data;
WebAssembly.instantiate(mod, importObject).then((instance) => {
instance.exports.exported_func();
});
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/module | data/mdn-content/files/en-us/webassembly/javascript_interface/module/customsections_static/index.md | ---
title: WebAssembly.Module.customSections()
slug: WebAssembly/JavaScript_interface/Module/customSections_static
page-type: webassembly-static-method
browser-compat: webassembly.api.Module.customSections_static
---
{{WebAssemblySidebar}}
The **`WebAssembly.Module.customSections()`** static method returns a copy
of the contents of all custom sections in the given module with the given string name.
## Syntax
```js-nolint
WebAssembly.Module.customSections(module, sectionName)
```
### Parameters
- `module`
- : The [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object whose custom sections are being
considered.
- `sectionName`
- : The string name of the desired custom section.
### Return value
A (possibly empty) array containing {{jsxref("ArrayBuffer")}} copies of the contents of all custom sections matching `sectionName`.
### Exceptions
If `module` is not a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object instance, a
{{jsxref("TypeError")}} is thrown.
## Description
A Wasm module consists of a sequence of **sections**. Most of these
sections are fully specified and validated by the Wasm spec, but modules can also
contain **custom sections** that are ignored and skipped over during
validation. (Read [High level structure](https://github.com/WebAssembly/design/blob/main/BinaryEncoding.md#high-level-structure)
for information on section structures, and how normal sections
("known sections") and custom sections are distinguished.)
This provides developers with a way to include custom data inside Wasm modules for other purposes,
for example the [name custom section](https://github.com/WebAssembly/design/blob/main/BinaryEncoding.md#name-section),
which allows developers to provide names for all the functions and
locals in the module (like "symbols" in a native build).
Note that the WebAssembly text format currently doesn't have a syntax specified for
adding new custom sections; you can however add a name section to your Wasm during
conversion from text format over to Wasm. The `wast2wasm` command available as part of
the [wabt tool](https://github.com/webassembly/wabt) has a
`--debug-names` option β specify this during conversion to get a Wasm with a
names custom section, for example:
```bash
wast2wasm simple-name-section.was -o simple-name-section.wasm --debug-names
```
## Examples
### Using customSections
The following example uses `WebAssembly.Module.customSections` to check
if a loaded module instance contains a "name" custom section. A module contains a "name" custom section if `WebAssembly.Module.customSections`
returns an `ArrayBuffer` with a length greater than 0.
See custom-section.html [source code](https://github.com/mdn/webassembly-examples/blob/main/other-examples/custom-section.html)
and [live example](https://mdn.github.io/webassembly-examples/other-examples/custom-section.html).
```js
WebAssembly.compileStreaming(fetch("simple-name-section.wasm")).then((mod) => {
const nameSections = WebAssembly.Module.customSections(mod, "name");
if (nameSections.length !== 0) {
console.log("Module contains a name section");
console.log(nameSections[0]);
}
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/module | data/mdn-content/files/en-us/webassembly/javascript_interface/module/exports_static/index.md | ---
title: WebAssembly.Module.exports()
slug: WebAssembly/JavaScript_interface/Module/exports_static
page-type: webassembly-static-method
browser-compat: webassembly.api.Module.exports_static
---
{{WebAssemblySidebar}}
The **`WebAssembly.Module.exports()`** static method returns an
array containing descriptions of all the declared exports of the given
`Module`.
## Syntax
```js-nolint
WebAssembly.Module.exports(module)
```
### Parameters
- `module`
- : A [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object.
### Return value
An array containing objects representing the exported functions of the given module.
### Exceptions
If module is not a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object instance, a
{{jsxref("TypeError")}} is thrown.
## Examples
### Using exports
The following example (see our [index-compile.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/index-compile.html)
demo on GitHub, and [view it live](https://mdn.github.io/webassembly-examples/js-api-examples/index-compile.html) also)
compiles the loaded simple.wasm byte code using the
[`WebAssembly.compileStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/compileStreaming_static) method and then sends it to a [worker](/en-US/docs/Web/API/Web_Workers_API) using [postMessage()](/en-US/docs/Web/API/Worker/postMessage).
```js
const worker = new Worker("wasm_worker.js");
WebAssembly.compileStreaming(fetch("simple.wasm")).then((mod) =>
worker.postMessage(mod),
);
```
In the worker (see
[`wasm_worker.js`](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/wasm_worker.js))
we define an import object for the module to use, then set up an event handler to
receive the module from the main thread. When the module is received, we create an
instance from it using the [`WebAssembly.Instantiate()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static) method, invoke an
exported function from inside it, then show how we can return information on the
available exports on a module using `WebAssembly.Module.exports`.
```js
const importObject = {
imports: {
imported_func(arg) {
console.log(arg);
},
},
};
onmessage = (e) => {
console.log("module received from main thread");
const mod = e.data;
WebAssembly.instantiate(mod, importObject).then((instance) => {
instance.exports.exported_func();
});
const exports = WebAssembly.Module.exports(mod);
console.log(exports[0]);
};
```
The `exports[0]` output looks like this:
```js
{ name: "exported_func", kind: "function" }
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/module | data/mdn-content/files/en-us/webassembly/javascript_interface/module/imports_static/index.md | ---
title: WebAssembly.Module.imports()
slug: WebAssembly/JavaScript_interface/Module/imports_static
page-type: webassembly-static-method
browser-compat: webassembly.api.Module.imports_static
---
{{WebAssemblySidebar}}
The **`WebAssembly.Module.imports()`** static method returns an array
containing descriptions of all the declared imports of the given `Module`.
## Syntax
```js-nolint
WebAssembly.Module.imports(module)
```
### Parameters
- `module`
- : A [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object.
### Return value
An array containing objects representing the imported functions of the given module.
### Exceptions
If module is not a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object instance, a
{{jsxref("TypeError")}} is thrown.
## Examples
### Using imports
The following example compiles a loaded Wasm module and queries the module's imports.
See imports.html [source code](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/imports.html) and
[live version](https://mdn.github.io/webassembly-examples/js-api-examples/imports.html).
```js
WebAssembly.compileStreaming(fetch("simple.wasm")).then((mod) => {
const imports = WebAssembly.Module.imports(mod);
console.log(imports[0]);
});
```
The console log displays the following description for the imported module:
```js
{ module: "imports", name: "imported_func", kind: "function" }
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/module | data/mdn-content/files/en-us/webassembly/javascript_interface/module/module/index.md | ---
title: WebAssembly.Module() constructor
slug: WebAssembly/JavaScript_interface/Module/Module
page-type: webassembly-constructor
browser-compat: webassembly.api.Module.Module
---
{{WebAssemblySidebar}}
A **`WebAssembly.Module()`** constructor creates a new Module
object containing stateless WebAssembly code that has already been compiled by the
browser and can be efficiently [shared with Workers](/en-US/docs/Web/API/Worker/postMessage), and instantiated multiple times.
The `WebAssembly.Module()` constructor function can be called to
synchronously compile given WebAssembly binary code. However, the primary way to get a
`Module` is through an asynchronous compilation function like
[`WebAssembly.compile()`](/en-US/docs/WebAssembly/JavaScript_interface/compile_static).
> **Note:** Webpages that have strict [Content Security Policy (CSP)](/en-US/docs/Web/HTTP/CSP) might block WebAssembly from compiling and executing modules.
> For more information on allowing WebAssembly compilation and execution, see the [script-src CSP](/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src).
## Syntax
> **Warning:** Since compilation for large modules can be expensive,
> developers should only use the `Module()` constructor when synchronous
> compilation is absolutely required; the asynchronous
> [`WebAssembly.compileStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/compileStreaming_static) method should be used at all other times.
```js-nolint
new WebAssembly.Module(bufferSource)
```
### Parameters
- `bufferSource`
- : A [typed array](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) or [ArrayBuffer](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)
containing the binary code of the Wasm module you want to compile.
#### Exceptions
- If the parameter is not of the correct type or structure, a
{{jsxref("TypeError")}} is thrown.
- If compilation fails, the constructor rejects with a
[`WebAssembly.CompileError`](/en-US/docs/WebAssembly/JavaScript_interface/CompileError).
- Some browsers may throw a {{jsxref("RangeError")}}, as they prohibit compilation and instantiation of Wasm with large buffers on the UI thread.
## Examples
### Synchronously compiling a WebAssembly module
```js
const importObject = {
imports: {
imported_func(arg) {
console.log(arg);
},
},
};
function createWasmModule(bytes) {
return new WebAssembly.Module(bytes);
}
fetch("simple.wasm")
.then((response) => response.arrayBuffer())
.then((bytes) => {
const mod = createWasmModule(bytes);
WebAssembly.instantiate(mod, importObject).then((result) =>
result.exports.exported_func(),
);
});
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/compileerror/index.md | ---
title: WebAssembly.CompileError
slug: WebAssembly/JavaScript_interface/CompileError
page-type: webassembly-interface
browser-compat: webassembly.api.CompileError
---
{{WebAssemblySidebar}}
The **`WebAssembly.CompileError`** object indicates an error during WebAssembly decoding or validation.
## Constructor
- [`WebAssembly.CompileError()`](/en-US/docs/WebAssembly/JavaScript_interface/CompileError/CompileError)
- : Creates a new `WebAssembly.CompileError` object.
## Instance properties
- {{jsxref("Error.prototype.message", "WebAssembly.CompileError.prototype.message")}}
- : Error message. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.name", "WebAssembly.CompileError.prototype.name")}}
- : Error name. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.cause", "WebAssembly.CompileError.prototype.cause")}}
- : Error cause. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.fileName", "WebAssembly.CompileError.prototype.fileName")}} {{non-standard_inline}}
- : Path to file that raised this error. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.lineNumber", "WebAssembly.CompileError.prototype.lineNumber")}} {{non-standard_inline}}
- : Line number in file that raised this error. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.columnNumber", "WebAssembly.CompileError.prototype.columnNumber")}} {{non-standard_inline}}
- : Column number in line that raised this error. Inherited from {{jsxref("Error")}}.
- {{jsxref("Error.prototype.stack", "WebAssembly.CompileError.prototype.stack")}} {{non-standard_inline}}
- : Stack trace. Inherited from {{jsxref("Error")}}.
## Instance methods
- {{jsxref("Error.prototype.toString", "WebAssembly.CompileError.prototype.toString()")}}
- : Returns a string representing the specified `Error` object. Inherited from {{jsxref("Error")}}.
## Examples
### Creating a new CompileError instance
The following snippet creates a new `CompileError` instance, and logs its details to the console:
```js
try {
throw new WebAssembly.CompileError("Hello", "someFile", 10);
} catch (e) {
console.log(e instanceof CompileError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "CompileError"
console.log(e.fileName); // "someFile"
console.log(e.lineNumber); // 10
console.log(e.columnNumber); // 0
console.log(e.stack); // returns the location where the code was run
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/compileerror | data/mdn-content/files/en-us/webassembly/javascript_interface/compileerror/compileerror/index.md | ---
title: WebAssembly.CompileError() constructor
slug: WebAssembly/JavaScript_interface/CompileError/CompileError
page-type: webassembly-constructor
browser-compat: webassembly.api.CompileError.CompileError
---
{{WebAssemblySidebar}}
The **`WebAssembly.CompileError()`** constructor creates a new
WebAssembly `CompileError` object, which indicates an error during
WebAssembly decoding or validation.
## Syntax
```js-nolint
new WebAssembly.CompileError()
new WebAssembly.CompileError(message)
new WebAssembly.CompileError(message, options)
new WebAssembly.CompileError(message, fileName)
new WebAssembly.CompileError(message, fileName, lineNumber)
```
### Parameters
- `message` {{optional_inline}}
- : Human-readable description of the error.
- `options` {{optional_inline}}
- : An object that has the following properties:
- `cause` {{optional_inline}}
- : A property indicating the specific cause of the error.
When catching and re-throwing an error with a more-specific or useful error message, this property can be used to pass the original error.
- `fileName` {{optional_inline}} {{non-standard_inline}}
- : The name of the file containing the code that caused the exception.
- `lineNumber` {{optional_inline}} {{non-standard_inline}}
- : The line number of the code that caused the exception.
## Examples
### Creating a new CompileError instance
The following snippet creates a new `CompileError` instance, and logs its
details to the console:
```js
try {
throw new WebAssembly.CompileError("Hello", "someFile", 10);
} catch (e) {
console.log(e instanceof CompileError); // true
console.log(e.message); // "Hello"
console.log(e.name); // "CompileError"
console.log(e.fileName); // "someFile"
console.log(e.lineNumber); // 10
console.log(e.columnNumber); // 0
console.log(e.stack); // returns the location where the code was run
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface | data/mdn-content/files/en-us/webassembly/javascript_interface/instance/index.md | ---
title: WebAssembly.Instance
slug: WebAssembly/JavaScript_interface/Instance
page-type: webassembly-interface
browser-compat: webassembly.api.Instance
---
{{WebAssemblySidebar}}
A **`WebAssembly.Instance`** object is a stateful, executable instance of a [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module). `Instance` objects contain all the [Exported WebAssembly functions](/en-US/docs/WebAssembly/Exported_functions) that allow calling into WebAssembly code from JavaScript.
## Constructor
- [`WebAssembly.Instance()`](/en-US/docs/WebAssembly/JavaScript_interface/Instance/Instance)
- : Creates a new `Instance` object.
## Instance properties
- [`exports`](/en-US/docs/WebAssembly/JavaScript_interface/Instance/exports)
- : Returns an object containing as its members all the functions exported from the WebAssembly module instance, to allow them to be accessed and used by JavaScript. Read-only.
## Examples
### Synchronously instantiating a WebAssembly module
The `WebAssembly.Instance()` constructor function can be called to synchronously instantiate a given [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object, for example:
```js
const importObject = {
imports: {
imported_func(arg) {
console.log(arg);
},
},
};
fetch("simple.wasm")
.then((response) => response.arrayBuffer())
.then((bytes) => {
const mod = new WebAssembly.Module(bytes);
const instance = new WebAssembly.Instance(mod, importObject);
instance.exports.exported_func();
});
```
The preferred way to get an `Instance` is asynchronously, for example using the [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) function like this:
```js
const importObject = {
imports: {
imported_func(arg) {
console.log(arg);
},
},
};
WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
(obj) => obj.instance.exports.exported_func(),
);
```
This also demonstrates how the `exports` property is used to access exported functions.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/instance | data/mdn-content/files/en-us/webassembly/javascript_interface/instance/exports/index.md | ---
title: WebAssembly.Instance.prototype.exports
slug: WebAssembly/JavaScript_interface/Instance/exports
page-type: webassembly-instance-property
browser-compat: webassembly.api.Instance.exports
---
{{WebAssemblySidebar}}
The **`exports`** readonly property of the
[`WebAssembly.Instance`](/en-US/docs/WebAssembly/JavaScript_interface/Instance) object prototype returns an object containing as its
members all the functions exported from the WebAssembly module instance, to allow them
to be accessed and used by JavaScript.
## Examples
### Using exports
After fetching some WebAssembly bytecode using fetch, we compile and instantiate the
module using the [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) function, importing a
JavaScript function into the WebAssembly Module in the process. We then call an [Exported WebAssembly function](/en-US/docs/WebAssembly/Exported_functions)
that is exported by the `Instance`.
```js
const importObject = {
imports: {
imported_func(arg) {
console.log(arg);
},
},
};
WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
(obj) => obj.instance.exports.exported_func(),
);
```
> **Note:** You can also find this example as [instantiate-streaming.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/instantiate-streaming.html)
> on GitHub ([view it live also](https://mdn.github.io/webassembly-examples/js-api-examples/instantiate-streaming.html)).
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly/javascript_interface/instance | data/mdn-content/files/en-us/webassembly/javascript_interface/instance/instance/index.md | ---
title: WebAssembly.Instance() constructor
slug: WebAssembly/JavaScript_interface/Instance/Instance
page-type: webassembly-constructor
browser-compat: webassembly.api.Instance.Instance
---
{{WebAssemblySidebar}}
The **`WebAssembly.Instance()`** constructor creates a new
`Instance` object which is a stateful, executable instance of a
[`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module).
## Syntax
> **Warning:** Since instantiation for large modules can be expensive,
> developers should only use the `Instance()` constructor when synchronous
> instantiation is absolutely required; the asynchronous
> [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) method should be used at all other
> times.
```js
new WebAssembly.Instance(module, importObject);
```
### Parameters
- `module`
- : The [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object to be instantiated.
- `importObject` {{optional_inline}}
- : An object containing the values to be imported into the newly-created
`Instance`, such as functions or [`WebAssembly.Memory`](/en-US/docs/WebAssembly/JavaScript_interface/Memory) objects.
There must be one matching property for each declared import of `module` or
else a [`WebAssembly.LinkError`](/en-US/docs/WebAssembly/JavaScript_interface/LinkError) is thrown.
#### Exceptions
- If either of the parameters are not of the correct type or structure, a
{{jsxref("TypeError")}} is thrown.
- If the operation fails, one of
[`WebAssembly.CompileError`](/en-US/docs/WebAssembly/JavaScript_interface/CompileError), [`WebAssembly.LinkError`](/en-US/docs/WebAssembly/JavaScript_interface/LinkError), or
[`WebAssembly.RuntimeError`](/en-US/docs/WebAssembly/JavaScript_interface/RuntimeError) are thrown, depending on the cause of the failure.
- Some browsers may throw a {{jsxref("RangeError")}}, as they prohibit compilation and instantiation of Wasm with large buffers on the UI thread.
## Examples
### Synchronously instantiating a WebAssembly module
The `WebAssembly.Instance()` constructor function can be called to
synchronously instantiate a given [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) object, for example:
```js
const importObject = {
imports: {
imported_func(arg) {
console.log(arg);
},
},
};
fetch("simple.wasm")
.then((response) => response.arrayBuffer())
.then((bytes) => {
const mod = new WebAssembly.Module(bytes);
const instance = new WebAssembly.Instance(mod, importObject);
instance.exports.exported_func();
});
```
However, the preferred way to get an `Instance` is through the asynchronous
[`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) function, for example like this:
```js
const importObject = {
imports: {
imported_func(arg) {
console.log(arg);
},
},
};
WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
(obj) => obj.instance.exports.exported_func(),
);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [WebAssembly](/en-US/docs/WebAssembly) overview page
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API)
| 0 |
data/mdn-content/files/en-us/webassembly | data/mdn-content/files/en-us/webassembly/exported_functions/index.md | ---
title: Exported WebAssembly functions
slug: WebAssembly/Exported_functions
page-type: guide
---
{{WebAssemblySidebar}}
Exported WebAssembly functions are how WebAssembly functions are represented in JavaScript. This article describes what they are in a little more detail.
## Exported⦠What?
Exported WebAssembly functions are basically just JavaScript wrappers that represent WebAssembly functions in JavaScript. When you call them, you get some activity in the background to convert the arguments into types that Wasm can work with (for example converting JavaScript numbers to Int32), the arguments are passed to the function inside your Wasm module, the function is invoked, and the result is converted and passed back to JavaScript.
You can retrieve exported WebAssembly functions in two ways:
- By calling [`Table.prototype.get()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/get) on an existing table.
- By accessing a function exported from a Wasm module instance via [`Instance.exports`](/en-US/docs/WebAssembly/JavaScript_interface/Instance/exports).
Either way, you get the same kind of wrapper for the underlying function. From a JavaScript point of view, it's as if every Wasm function _is_ a JavaScript function too β but they are encapsulated by the exported Wasm function object instance and there are only limited ways to access them.
## An example
Let's look at an example to clear things up (you can find this on GitHub as [table-set.html](https://github.com/mdn/webassembly-examples/blob/main/other-examples/table-set.html); see it [running live also](https://mdn.github.io/webassembly-examples/other-examples/table-set.html), and check out the Wasm [text representation](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/table.wat)):
```js
const otherTable = new WebAssembly.Table({ element: "anyfunc", initial: 2 });
WebAssembly.instantiateStreaming(fetch("table.wasm")).then((obj) => {
const tbl = obj.instance.exports.tbl;
console.log(tbl.get(0)()); // 13
console.log(tbl.get(1)()); // 42
otherTable.set(0, tbl.get(0));
otherTable.set(1, tbl.get(1));
console.log(otherTable.get(0)());
console.log(otherTable.get(1)());
});
```
Here we create a table (`otherTable`) from JavaScript using the [`WebAssembly.Table`](/en-US/docs/WebAssembly/JavaScript_interface/Table) constructor, then we load `table.wasm` into our page using the [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) method.
We then get the function exported from the module, retrieve the functions it references via [`tbl.get()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/get) and log the result of invoking each one to the console. Next, we use `set()` to make the `otherTable` table contain references to the same functions as the `tbl` table.
To prove this, we then retrieve these references back from `otherTable` and print their results to console too, which gives the same results.
## They are real functions
In the previous example, the return value of each [`Table.prototype.get()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/get) call is an exported WebAssembly function β exactly what we have been talking about.
It is worth noting that these are real JavaScript functions, in addition to being wrappers for WebAssembly functions. If you load the above example in a [WebAssembly-supporting browser](/en-US/docs/WebAssembly#browser_compatibility), and run the following lines in your console:
```js
const testFunc = otherTable.get(0);
typeof testFunc;
```
you'll get the result `function` returned. You can then go on to do pretty much anything to this function that you can do to other [functions](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function) in JavaScript β [`call()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call), [`bind()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind), etc. `testFunc.toString()` returns an interesting result:
```plain
function 0() {
[native code]
}
```
This gives you more of an idea of its wrapper-type nature.
Some other particulars to be aware of with exported WebAssembly functions:
- Their [length](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length) property is the number of declared arguments in the Wasm function signature.
- Their [name](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name) property is the `toString()` result of the function's index in the Wasm module.
- If you try to call an exported Wasm function that takes or returns an i64 type value, it currently throws an error because JavaScript currently has no precise way to represent an i64. This may well change in the future though β a new int64 type is being considered for future standards, which could then be used by Wasm.
| 0 |
data/mdn-content/files/en-us/webassembly | data/mdn-content/files/en-us/webassembly/text_format_to_wasm/index.md | ---
title: Converting WebAssembly text format to Wasm
slug: WebAssembly/Text_format_to_Wasm
page-type: guide
---
{{WebAssemblySidebar}}
WebAssembly has an S-expression-based textual representation, an intermediate form designed to be exposed in text editors, browser developer tools, etc. This article explains a little bit about how it works, and how to use available tools to convert text format files to the Wasm format.
> **Note:** Text format files are usually saved with a `.wat` extension. Historically, a `.wast` extension was also used, however that's now used for the scripting language used by the WebAssembly test suite.
## A first look at the text format
Let's look at a simple example of this β the following program imports a function called `imported_func` from a module called `imports`, and exports a function called `exported_func`:
```wasm
(module
(func $i (import "imports" "imported_func") (param i32))
(func (export "exported_func")
i32.const 42
call $i
)
)
```
The WebAssembly function `exported_func` is exported for use in our environment (e.g. the web app in which we are using our WebAssembly module). When it is called, it calls an imported JavaScript function called `imported_func`, which is run with the value (42) provided as a parameter.
## Converting the text .wat into a binary .wasm file
Let's have a go at converting the above `.wat` text representation example into `.wasm` assembly format.
1. To start with, make a copy of the above listing inside a text file; call it `simple.wat`.
2. We need to assemble this textual representation into the assembly language the browser actually reads before we can use it. To do this, we can use the wabt tool, which includes compilers to convert between WebAssembly's text representation and Wasm, and vice versa, plus more besides. Go to <https://github.com/webassembly/wabt> β follow the instructions on this page to set up the tool.
3. Once you've got the tool built, add the `/wabt/out/clang/Debug` directory to your system `PATH`.
4. Next, execute the wat2wasm program, passing it the path to the input file, followed by an `-o` parameter, followed by the path to the output file:
```bash
wat2wasm simple.wat -o simple.wasm
```
This will convert the Wasm into a file called `simple.wasm`, which contains the `.wasm` assembly code.
> **Note:** You can also convert the assembly back into the text representation using the wasm2wat tool; for example `wasm2wat simple.wasm -o text.wat`.
## Viewing the assembly output
Because the output file is assembly-based, it can't be viewed in a normal text editor. However, you can view it using the wat2wasm tool's `-v` option. Try this:
```bash
wat2wasm simple.wat -v
```
This will give you an output in your terminal in the following way:

## See also
- [Understanding WebAssembly text format](/en-US/docs/WebAssembly/Understanding_the_text_format) β a detailed explanation of the text format syntax.
- [Compiling from C/C++ to WebAssembly](/en-US/docs/WebAssembly/C_to_Wasm) β tools like Binaryen/Emscripten both compile your source code to Wasm, and create the API code needed to run the module in a JavaScript context. Find out more about how to use them.
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API) β read this if you want to find out more about how the WebAssembly API code works.
- [Text format](https://webassembly.github.io/spec/core/text/index.html) β more explanation of the text format, on the WebAssembly GitHub repo.
- [wast-loader](https://github.com/xtuc/webassemblyjs/tree/master/packages/wast-loader) β a loader for webpack that takes care of all of this for you.
| 0 |
data/mdn-content/files/en-us/webassembly | data/mdn-content/files/en-us/webassembly/rust_to_wasm/index.md | ---
title: Compiling from Rust to WebAssembly
slug: WebAssembly/Rust_to_Wasm
page-type: guide
---
{{WebAssemblySidebar}}
If you have some Rust code, you can compile it into [WebAssembly](/en-US/docs/WebAssembly) (Wasm). This tutorial will show you how to compile a Rust project into WebAssembly and use it in an existing web app.
## Rust and WebAssembly use cases
There are two main use cases for Rust and WebAssembly:
- Build an entire application β an entire web app based in Rust.
- Build a part of an application β using Rust in an existing JavaScript frontend.
For now, the Rust team is focusing on the latter case, and so that's what we cover here. For the former case, check out projects like [`yew`](https://github.com/yewstack/yew).
In this tutorial, we build a package using `wasm-pack`, a tool for building JavaScript packages in Rust. This package will contain only WebAssembly and JavaScript code, and so the users of the package won't need Rust installed. They may not even notice that it's written in Rust.
## Rust Environment Setup
Let's go through all the required steps to get our environment set up.
### Install Rust
Install Rust by going to the [Install Rust](https://www.rust-lang.org/tools/install) page and following the instructions. This installs a tool called "rustup", which lets you manage multiple versions of Rust. By default, it installs the latest stable Rust release, which you can use for general Rust development. Rustup installs `rustc`, the Rust compiler, as well as `cargo`, Rust's package manager, `rust-std`, Rust's standard libraries, and some helpful docs β `rust-docs`.
> **Note:** Pay attention to the post-install note about needing cargo's `bin` directory in your system `PATH`. This is added automatically, but you must restart your terminal for it to take effect.
### wasm-pack
To build the package, we need an additional tool, `wasm-pack`. This helps compile the code to WebAssembly, as well as produce the right packaging for use in the browser. To download and install it, enter the following command into your terminal:
```bash
cargo install wasm-pack
```
## Building our WebAssembly package
Enough setup; let's create a new package in Rust. Navigate to wherever you keep your personal projects, and type this:
```bash
cargo new --lib hello-wasm
```
This creates a new library in a subdirectory named `hello-wasm` with everything you need to get going:
```plain
βββ Cargo.toml
βββ src
βββ lib.rs
```
First, we have `Cargo.toml`; this is the file that we use to configure our build. If you've used `Gemfile` from Bundler or `package.json` from npm, this is likely to be familiar; Cargo works in a similar manner to both of them.
Next, Cargo has generated some Rust code for us in `src/lib.rs`:
```rust
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
```
We won't use this test code at all, so go ahead and delete it.
### Let's write some Rust
Let's put this code into `src/lib.rs` instead:
```rust
use wasm_bindgen::prelude::*;
#[wasm_bindgen]
extern {
pub fn alert(s: &str);
}
#[wasm_bindgen]
pub fn greet(name: &str) {
alert(&format!("Hello, {}!", name));
}
```
This is the contents of our Rust project. It has three main parts; let's talk about each of them in turn. We give a high-level explanation here, and gloss over some details; to learn more about Rust, please check the free online book [The Rust Programming Language](https://doc.rust-lang.org/book/).
#### Using `wasm-bindgen` to communicate between Rust and JavaScript
The first part looks like this:
```rust
use wasm_bindgen::prelude::*;
```
Libraries are called "crates" in Rust.
Get it? _Cargo_ ships _crates_.
The first line contains a `use` command, which imports code from a library into your code. In this case, we're importing everything in the `wasm_bindgen::prelude` module. We use these features in the next section.
Before we move on to the next section, we should talk a bit more about `wasm-bindgen`.
`wasm-pack` uses `wasm-bindgen`, another tool, to provide a bridge between the types of JavaScript and Rust. It allows JavaScript to call a Rust API with a string, or a Rust function to catch a JavaScript exception.
We use `wasm-bindgen`'s functionality in our package. In fact, that's the next section.
#### Calling external functions in JavaScript from Rust
The next part looks like this:
```rust
#[wasm_bindgen]
extern {
pub fn alert(s: &str);
}
```
The bit inside the `#[ ]` is called an "attribute", and it modifies the next statement somehow. In this case, that statement is an `extern`, which tells Rust that we want to call some externally defined functions. The attribute says "wasm-bindgen knows how to find these functions".
The third line is a function signature, written in Rust. It says "the `alert` function takes one argument, a string named `s`."
As you might suspect, this is [the `alert` function provided by JavaScript](/en-US/docs/Web/API/Window/alert). We call this function in the next section.
Whenever you want to call JavaScript functions, you can add them to this file, and `wasm-bindgen` takes care of setting everything up for you. Not everything is supported yet, but we're working on it. Please [file bugs](https://github.com/rustwasm/wasm-bindgen/issues/new) if something is missing.
#### Producing Rust functions that JavaScript can call
The final part is this one:
```rust
#[wasm_bindgen]
pub fn greet(name: &str) {
alert(&format!("Hello, {}!", name));
}
```
Once again, we see the `#[wasm_bindgen]` attribute. In this case, it's not modifying an `extern` block, but a `fn`; this means that we want this Rust function to be able to be called by JavaScript. It's the opposite of `extern`: these aren't the functions we need, but rather the functions we're giving out to the world.
This function is named `greet`, and takes one argument, a string (written `&str`), `name`. It then calls the `alert` function we asked for in the `extern` block above. It passes a call to the `format!` macro, which lets us concatenate strings.
The `format!` macro takes two arguments in this case, a format string, and a variable to put in it. The format string is the `"Hello, {}!"` bit. It contains `{}`s, where variables will be interpolated. The variable we're passing is `name`, the argument to the function, so if we call `greet("Steve")` we should see `"Hello, Steve!".`
This is passed to `alert()`, so when we call this function we will see an alert box with "Hello, Steve!" in it.
Now that our library is written, let's build it.
### Compiling our code to WebAssembly
To compile our code correctly, we first need to configure it with `Cargo.toml`. Open this file, and change its contents to look like this:
```toml
[package]
name = "hello-wasm"
version = "0.1.0"
authors = ["Your Name <[email protected]>"]
description = "A sample project with wasm-pack"
license = "MIT/Apache-2.0"
repository = "https://github.com/yourgithubusername/hello-wasm"
edition = "2018"
[lib]
crate-type = ["cdylib"]
[dependencies]
wasm-bindgen = "0.2"
```
Fill in your own repository and use the same info that `git` uses for the `authors` field.
The big part to add is the `[package]`. The `[lib]` part tells Rust to build a `cdylib` version of our package; we won't get into what that means in this tutorial. For more, consult the [Cargo](https://doc.rust-lang.org/cargo/guide/) and [Rust Linkage](https://doc.rust-lang.org/reference/linkage.html) documentation.
The last section is the `[dependencies]` section. Here's where we tell Cargo what version of `wasm-bindgen` we want to depend on; in this case, that's any `0.2.z` version (but not `0.3.0` or above).
### Building the package
Now that we've got everything set up, let's build the package.
We'll be using the generated code in a native ES module and in Node.js.
For this purpose, we'll use the [`--target` argument](https://rustwasm.github.io/docs/wasm-pack/commands/build.html#target) in `wasm-pack build` to specify what kind of WebAssembly and JavaScript is generated.
Firstly, run the following command:
```bash
wasm-pack build --target web
```
This does a number of things (and they take a lot of time, especially the first time you run `wasm-pack`). To learn about them in detail, check out [this blog post on Mozilla Hacks](https://hacks.mozilla.org/2018/04/hello-wasm-pack/). In short, `wasm-pack build`:
1. Compiles your Rust code to WebAssembly.
2. Runs `wasm-bindgen` on that WebAssembly, generating a JavaScript file that wraps up that WebAssembly file into a module the browser can understand.
3. Creates a `pkg` directory and moves that JavaScript file and your WebAssembly code into it.
4. Reads your `Cargo.toml` and produces an equivalent `package.json`.
5. Copies your `README.md` (if you have one) into the package.
The end result? You have a package inside the `pkg` directory.
#### A digression about code size
If you check out the generated WebAssembly code size, it may be a few hundred kilobytes. We haven't instructed Rust to optimize for size at all, and doing so cuts down on the size _a lot_. This is beyond the scope of this tutorial, but if you'd like to learn more, check out the Rust WebAssembly Working Group's documentation on [Shrinking .wasm Size](https://rustwasm.github.io/book/game-of-life/code-size.html#shrinking-wasm-size).
## Using the package on the web
Now that we've got a compiled Wasm module, let's run it in the browser.
Let's start by creating a file named `index.html` in the root of the project, so we end up with the following project structure:
```plain
βββ Cargo.lock
βββ Cargo.toml
βββ index.html <-- new index.html file
βββ pkg
β βββ hello_wasm.d.ts
β βββ hello_wasm.js
β βββ hello_wasm_bg.wasm
β βββ hello_wasm_bg.wasm.d.ts
β βββ package.json
βββ src
β βββ lib.rs
βββ target
βββ CACHEDIR.TAG
βββ release
βββ wasm32-unknown-unknown
```
Put the following content in the `index.html` file:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>hello-wasm example</title>
</head>
<body>
<script type="module">
import init, { greet } from "./pkg/hello_wasm.js";
init().then(() => {
greet("WebAssembly");
});
</script>
</body>
</html>
```
The script in this file will import the JavaScript glue code, initialize the Wasm module, and call the `greet` function we wrote in Rust.
Serve the root directory of the project with a local web server, (e.g. `python3 -m http.server`). If you're not sure how to do that, refer to [Running a simple local HTTP server](/en-US/docs/Learn/Common_questions/Tools_and_setup/set_up_a_local_testing_server#running_a_simple_local_http_server).
> **Note:** Make sure to use an up-to-date web server that supports the `application/wasm` MIME type. Older web servers might not support it yet.
Load `index.html` from the web server (if you used the Python3 example: `http://localhost:8000`). An alert box appears on the screen, with `Hello, WebAssembly!` in it. We've successfully called from JavaScript into Rust, and from Rust into JavaScript.
## Making our package available to npm
We are building an npm package, so you need to have Node.js and npm installed.
To get Node.js and npm, go to the [Get npm!](https://docs.npmjs.com/getting-started/) page and follow the instructions.
This tutorial targets node 20. If you need to switch between node versions, you can use [nvm](https://github.com/nvm-sh/nvm).
If you want to use the WebAssembly module with npm, we'll need to make a few changes.
Let's start by recompiling our Rust with `bundler` option as the target:
```bash
wasm-pack build --target bundler
```
We now have an npm package, written in Rust, but compiled to WebAssembly. It's ready for use from JavaScript, and doesn't require the user to have Rust installed; the code included was the WebAssembly code, not the Rust source.
### Using the npm package on the web
Let's build a website that uses our new npm package. Many people use npm packages through various bundler tools, and we'll be using one of them, `webpack`, in this tutorial. It's only a bit complex, and shows a realistic use-case.
Let's move back out of the `pkg` directory, and make a new directory, `site`, to try this out.
We haven't published the package to the npm registry yet, so we can install it from a local version using `npm i /path/to/package`.
You may use [`npm link`](https://docs.npmjs.com/cli/v10/commands/npm-link), but installing from a local path is convenient for the purposes of this demo:
```bash
cd ..
mkdir site && cd site
npm i ../pkg
```
Install the `webpack` dev dependencies:
```bash
npm i -D webpack@5 webpack-cli@5 webpack-dev-server@4 copy-webpack-plugin@11
```
Next, we need to configure Webpack. Create `webpack.config.js` and put the following in it:
```js
const CopyPlugin = require("copy-webpack-plugin");
const path = require("path");
module.exports = {
entry: "./index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.js",
},
mode: "development",
experiments: {
asyncWebAssembly: true,
},
plugins: [
new CopyPlugin({
patterns: [{ from: "index.html" }],
}),
],
};
```
In your `package.json`, you can add `build` and `serve` scripts that will run webpack with the config file we just created:
```json
{
"scripts": {
"build": "webpack --config webpack.config.js",
"serve": "webpack serve --config webpack.config.js --open"
},
"dependencies": {
"hello-wasm": "file:../pkg"
},
"devDependencies": {
"copy-webpack-plugin": "^11.0.0",
"webpack": "^5.89.0",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.15.1"
}
}
```
Next, create a file named `index.js`, and give it these contents:
```js
import * as wasm from "hello-wasm";
wasm.greet("WebAssembly with npm");
```
This imports the module from the `node_modules` folder and calls the `greet` function, passing `"WebAssembly with npm"` as a string. Note how there's nothing special here, yet we're calling into Rust code. As far as the JavaScript code can tell, this is just a normal module.
Finally, we need to add a HTML file to load the JavaScript. Create an `index.html` file and add the following:
```html
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>hello-wasm example</title>
</head>
<body>
<script src="./index.js"></script>
</body>
</html>
```
The `hello-wasm/site` directory should look like this:
```plain
βββ index.html
βββ index.js
βββ node_modules
βββ package-lock.json
βββ package.json
βββ webpack.config.js
```
We're done making files. Let's give this a shot:
```bash
npm run serve
```
This starts a web server and opens `http://localhost:8080`. You should see an alert box appears on the screen, with `Hello, WebAssembly with npm!` in it. We've successfully used the Rust module with npm!
If you would like to use your WebAssembly outside of local development, you can publish the package using the `pack` and `publish` commands:
```bash
wasm-pack pack
npm notice
npm notice π¦ [email protected]
npm notice === Tarball Contents ===
npm notice 1.6kB README.md
npm notice 2.5kB hello_wasm_bg.js
npm notice 17.5kB hello_wasm_bg.wasm
npm notice 115B hello_wasm.d.ts
npm notice 157B hello_wasm.js
npm notice 531B package.json
...
hello-wasm-0.1.0.tgz
[INFO]: π packed up your package!
```
To publish to npm, you will need an [npm account](https://www.npmjs.com/) and authorize your machine using [`npm adduser`](https://docs.npmjs.com/cli/v10/commands/npm-adduser).
When you are ready, you can publish using `wasm-pack` which calls `npm publish` under the hood:
```bash
wasm-pack publish
```
## Conclusion
This is the end of our tutorial; we hope you've found it useful.
There's lots of exciting work going on in this space; if you'd like to help make it even better, check out the [Rust and WebAssembly Working Group](https://github.com/rustwasm/team/blob/master/README.md#get-involved).
| 0 |
data/mdn-content/files/en-us/webassembly | data/mdn-content/files/en-us/webassembly/existing_c_to_wasm/index.md | ---
title: Compiling an Existing C Module to WebAssembly
slug: WebAssembly/existing_C_to_Wasm
page-type: guide
---
{{WebAssemblySidebar}}
A core use-case for WebAssembly is to take the existing ecosystem of C libraries and allow developers to use them on the web.
These libraries often rely on C's standard library, an operating system, a file system and other things. Emscripten provides most of these features, although there are some [limitations](https://emscripten.org/docs/porting/guidelines/api_limitations.html).
As an example, let's compile an encoder for WebP to Wasm. The source for the WebP codec is written in C and [available on GitHub](https://github.com/webmproject/libwebp) as well as some extensive [API documentation](https://developers.google.com/speed/webp/docs/api). That's a pretty good starting point.
```bash
git clone https://github.com/webmproject/libwebp
```
To start off simple, expose `WebPGetEncoderVersion()` from `encode.h` to JavaScript by writing a C file called `webp.c`:
```cpp
#include "emscripten.h"
#include "src/webp/encode.h"
EMSCRIPTEN_KEEPALIVE
int version() {
return WebPGetEncoderVersion();
}
```
This is a good simple program to test whether you can get the source code of libwebp to compile, as it doesn't require any parameters or complex data structures to invoke this function.
To compile this program, you need to tell the compiler where it can find libwebp's header files using the `-I` flag and also pass it all the C files of libwebp that it needs. A useful strategy is to just give it **all** the C files and rely on the compiler to strip out everything that is unnecessary. It seems to work brilliantly for this library:
```bash
emcc -O3 -s WASM=1 -s EXPORTED_RUNTIME_METHODS='["cwrap"]' \
-I libwebp \
webp.c \
libwebp/src/{dec,dsp,demux,enc,mux,utils}/*.c \
libwebp/sharpyuv/*.c
```
> **Note:** This strategy will not work with every C project. Many projects rely on autoconf/automake to generate system-specific code before compilation. Emscripten provides `emconfigure` and `emmake` to wrap these commands and inject the appropriate parameters. You can find more in the [Emscripten documentation](https://emscripten.org/docs/compiling/Building-Projects.html).
Now you only need some HTML and JavaScript to load your new module:
```html
<script src="./a.out.js"></script>
<script>
Module.onRuntimeInitialized = async () => {
const api = {
version: Module.cwrap("version", "number", []),
};
console.log(api.version());
};
</script>
```
And you will see the correct version number in the [output](https://googlechrome.github.io/samples/webassembly/version.html):

> **Note:** libwebp returns the current version a.b.c as a hexadecimal number 0xabc. For example, v0.6.1 is encoded as 0x000601 = 1537.
### Get an image from JavaScript into Wasm
Getting the encoder's version number is great, but encoding an actual image would be more impressive. How do we do that?
The first question you need to answer is: how do I get the image into Wasm? Looking at the [encoding API of libwebp](https://developers.google.com/speed/webp/docs/api#simple_encoding_api), you'll find that it expects an array of bytes in RGB, RGBA, BGR or BGRA. Luckily, the Canvas API has {{domxref("CanvasRenderingContext2D.getImageData")}} β that gives you a {{jsxref("Uint8ClampedArray")}} containing the image data in RGBA:
```js
async function loadImage(src) {
// Load image
const imgBlob = await fetch(src).then((resp) => resp.blob());
const img = await createImageBitmap(imgBlob);
// Make canvas same size as image
const canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
// Draw image onto canvas
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
return ctx.getImageData(0, 0, img.width, img.height);
}
```
Now it's "only" a matter of copying the data from JavaScript into Wasm. For that, you need to expose two additional functions β one that allocates memory for the image inside Wasm and one that frees it up again:
```cpp
#include <stdlib.h> // required for malloc definition
EMSCRIPTEN_KEEPALIVE
uint8_t* create_buffer(int width, int height) {
return malloc(width * height * 4 * sizeof(uint8_t));
}
EMSCRIPTEN_KEEPALIVE
void destroy_buffer(uint8_t* p) {
free(p);
}
```
The `create_buffer()` function allocates a buffer for the RGBA image β hence 4 bytes per pixel. The pointer returned by `malloc()` is the address of the first memory cell of that buffer. When the pointer is returned to JavaScript land, it is treated as just a number. After exposing the function to JavaScript using cwrap, you can use that number to find the start of our buffer and copy the image data:
```js
const api = {
version: Module.cwrap("version", "number", []),
create_buffer: Module.cwrap("create_buffer", "number", ["number", "number"]),
destroy_buffer: Module.cwrap("destroy_buffer", "", ["number"]),
encode: Module.cwrap("encode", "", ["number", "number", "number", "number"]),
free_result: Module.cwrap("free_result", "", ["number"]),
get_result_pointer: Module.cwrap("get_result_pointer", "number", []),
get_result_size: Module.cwrap("get_result_size", "number", []),
};
const image = await loadImage("./image.jpg");
const p = api.create_buffer(image.width, image.height);
Module.HEAP8.set(image.data, p);
// ... call encoder ...
api.destroy_buffer(p);
```
### Encode the Image
The image is now available in Wasm. It is time to call the WebP encoder to do its job. Looking at the [WebP documentation](https://developers.google.com/speed/webp/docs/api#simple_encoding_api), you'll find that `WebPEncodeRGBA` seems like a perfect fit. The function takes a pointer to the input image and its dimensions, as well as a quality option between 0 and 100. It also allocates an output buffer for us that we need to free using `WebPFree()` once we are done with the WebP image.
The result of the encoding operation is an output buffer and its length. Because functions in C can't have arrays as return types (unless you allocate memory dynamically), this example resorts to a static global array. This may not be clean C. In fact, it relies on Wasm pointers being 32 bits wide. But this is a fair shortcut for keeping things simple:
```cpp
int result[2];
EMSCRIPTEN_KEEPALIVE
void encode(uint8_t* img_in, int width, int height, float quality) {
uint8_t* img_out;
size_t size;
size = WebPEncodeRGBA(img_in, width, height, width * 4, quality, &img_out);
result[0] = (int)img_out;
result[1] = size;
}
EMSCRIPTEN_KEEPALIVE
void free_result(uint8_t* result) {
WebPFree(result);
}
EMSCRIPTEN_KEEPALIVE
int get_result_pointer() {
return result[0];
}
EMSCRIPTEN_KEEPALIVE
int get_result_size() {
return result[1];
}
```
Now with all of that in place, you can call the encoding function, grab the pointer and image size, put it in a JavaScript buffer of your own, and release all the Wasm buffers allocated in the process:
```js
api.encode(p, image.width, image.height, 100);
const resultPointer = api.get_result_pointer();
const resultSize = api.get_result_size();
const resultView = new Uint8Array(
Module.HEAP8.buffer,
resultPointer,
resultSize,
);
const result = new Uint8Array(resultView);
api.free_result(resultPointer);
```
> **Note:** `new Uint8Array(someBuffer)` will create a new view onto the same memory chunk, while `new Uint8Array(someTypedArray)` will copy the data.
Depending on the size of your image, you might run into an error where Wasm can't grow the memory enough to accommodate both the input and the output image:

Luckily, the solution to this problem is in the error message. You just need to add `-s ALLOW_MEMORY_GROWTH=1` to your compilation command.
And there you have it. You have compiled a WebP encoder and transcoded a JPEG image to WebP. To prove that it worked, turn your result buffer into a blob and use it on an `<img>` element:
```js
const blob = new Blob([result], { type: "image/webp" });
const blobURL = URL.createObjectURL(blob);
const img = document.createElement("img");
img.src = blobURL;
img.alt = "a useful description";
document.body.appendChild(img);
```
Behold, the glory of a new WebP image.
[Demo](https://googlechrome.github.io/samples/webassembly/image.html) | [Original Article](https://web.dev/articles/emscripting-a-c-library)

| 0 |
data/mdn-content/files/en-us/webassembly | data/mdn-content/files/en-us/webassembly/concepts/index.md | ---
title: WebAssembly Concepts
slug: WebAssembly/Concepts
page-type: guide
---
{{WebAssemblySidebar}}
This article explains the concepts behind how WebAssembly works including its goals, the problems it solves, and how it runs inside the web browser's JavaScript engine.
## What is WebAssembly?
WebAssembly is a new type of code that can be run in modern web browsers and provides new features and major gains in performance. It is not primarily intended to be written by hand, rather it is designed to be an effective compilation target for source languages like C, C++, Rust, etc.
This has huge implications for the web platform β it provides a way to run code written in multiple languages on the web at near-native speed, with client apps running on the web that previously couldn't have done so.
What's more, you don't even have to know how to create WebAssembly code to take advantage of it. WebAssembly modules can be imported into a web (or Node.js) app, exposing WebAssembly functions for use via JavaScript. JavaScript frameworks could make use of WebAssembly to confer massive performance advantages and new features while still making functionality easily available to web developers.
## WebAssembly goals
WebAssembly is being created as an open standard inside the [W3C WebAssembly Community Group](https://www.w3.org/community/webassembly/) with the following goals:
- Be fast, efficient, and portable β WebAssembly code can be executed at near-native speed across different platforms by taking advantage of [common hardware capabilities](https://webassembly.org/docs/portability/#assumptions-for-efficient-execution).
- Be readable and debuggable β WebAssembly is a low-level assembly language, but it does have a human-readable text format (the specification for which is still being finalized) that allows code to be written, viewed, and debugged by hand.
- Keep secure β WebAssembly is specified to be run in a safe, sandboxed execution environment. Like other web code, it will enforce the browser's same-origin and permissions policies.
- Don't break the web β WebAssembly is designed so that it plays nicely with other web technologies and maintains backwards compatibility.
> **Note:** WebAssembly will also have uses outside web and JavaScript environments (see [Non-web embeddings](https://webassembly.org/docs/non-web/)).
## How does WebAssembly fit into the web platform?
The web platform can be thought of as having two parts:
- A virtual machine (VM) that runs the Web app's code, e.g. the JavaScript code that powers your apps.
- A set of [Web APIs](/en-US/docs/Web/API) that the Web app can call to control web browser/device functionality and make things happen ([DOM](/en-US/docs/Web/API/Document_Object_Model), [CSSOM](/en-US/docs/Web/API/CSS_Object_Model), [WebGL](/en-US/docs/Web/API/WebGL_API), [IndexedDB](/en-US/docs/Web/API/IndexedDB_API), [Web Audio API](/en-US/docs/Web/API/Web_Audio_API), etc.).
Historically, the VM has been able to load only JavaScript. This has worked well for us as JavaScript is powerful enough to solve most problems people have on the Web today. We have run into performance problems, however, when trying to use JavaScript for more intensive use cases like 3D games, Virtual and Augmented Reality, computer vision, image/video editing, and a number of other domains that demand native performance (see [WebAssembly use cases](https://webassembly.org/docs/use-cases/) for more ideas).
Additionally, the cost of downloading, parsing, and compiling very large JavaScript applications can be prohibitive. Mobile and other resource-constrained platforms can further amplify these performance bottlenecks.
WebAssembly is a different language from JavaScript, but it is not intended as a replacement. Instead, it is designed to complement and work alongside JavaScript, allowing web developers to take advantage of both languages' strong points:
- JavaScript is a high-level language, flexible and expressive enough to write web applications. It has many advantages β it is dynamically typed, requires no compile step, and has a huge ecosystem that provides powerful frameworks, libraries, and other tools.
- WebAssembly is a low-level assembly-like language with a compact binary format that runs with near-native performance and provides languages with low-level memory models such as C++ and Rust with a compilation target so that they can run on the web. (Note that WebAssembly has the [high-level goal](https://webassembly.org/docs/high-level-goals/) of supporting languages with garbage-collected memory models in the future.)
With the advent of WebAssembly appearing in browsers, the virtual machine that we talked about earlier will now load and run two types of code β JavaScript AND WebAssembly.
The different code types can call each other as required β the [WebAssembly JavaScript API](/en-US/docs/WebAssembly/JavaScript_interface) wraps exported WebAssembly code with JavaScript functions that can be called normally, and WebAssembly code can import and synchronously call normal JavaScript functions. In fact, the basic unit of WebAssembly code is called a module and WebAssembly modules are symmetric in many ways to ES modules.
### WebAssembly key concepts
There are several key concepts needed to understand how WebAssembly runs in the browser. All of these concepts are reflected 1:1 in the [WebAssembly JavaScript API](/en-US/docs/WebAssembly/JavaScript_interface).
- **Module**: Represents a WebAssembly binary that has been compiled by the browser into executable machine code. A Module is stateless and thus, like a [`Blob`](/en-US/docs/Web/API/Blob), can be explicitly shared between windows and workers (via [`postMessage()`](/en-US/docs/Web/API/MessagePort/postMessage)). A Module declares imports and exports just like an ES module.
- **Memory**: A resizable ArrayBuffer that contains the linear array of bytes read and written by WebAssembly's low-level memory access instructions.
- **Table**: A resizable typed array of references (e.g. to functions) that could not otherwise be stored as raw bytes in Memory (for safety and portability reasons).
- **Instance**: A Module paired with all the state it uses at runtime including a Memory, Table, and set of imported values. An Instance is like an ES module that has been loaded into a particular global with a particular set of imports.
The JavaScript API provides developers with the ability to create modules, memories, tables, and instances. Given a WebAssembly instance, JavaScript code can synchronously call its exports, which are exposed as normal JavaScript functions. Arbitrary JavaScript functions can also be synchronously called by WebAssembly code by passing in those JavaScript functions as the imports to a WebAssembly instance.
Since JavaScript has complete control over how WebAssembly code is downloaded, compiled and run, JavaScript developers could even think of WebAssembly as just a JavaScript feature for efficiently generating high-performance functions.
In the future, WebAssembly modules will be [loadable just like ES modules](https://github.com/WebAssembly/proposals/issues/12) (using `<script type='module'>`), meaning that JavaScript will be able to fetch, compile, and import a WebAssembly module as easily as an ES module.
## How do I use WebAssembly in my app?
Above we talked about the raw primitives that WebAssembly adds to the Web platform: a binary format for code and APIs for loading and running this binary code. Now let's talk about how we can use these primitives in practice.
The WebAssembly ecosystem is at a nascent stage; more tools will undoubtedly emerge going forward. Right now, there are four main entry points:
- Porting a C/C++ application with [Emscripten](https://emscripten.org/).
- Writing or generating WebAssembly directly at the assembly level.
- Writing a Rust application and targeting WebAssembly as its output.
- Using [AssemblyScript](https://www.assemblyscript.org/) which looks similar to TypeScript and compiles to WebAssembly binary.
Let's talk about these options:
### Porting from C/C++
Two of the many options for creating Wasm code are an online Wasm assembler or [Emscripten](https://emscripten.org/). There are a number of online Wasm assembler choices, such as:
- [WasmFiddle++](https://anonyco.github.io/WasmFiddlePlusPlus/)
- [WasmExplorer](https://mbebenita.github.io/WasmExplorer/)
These are great resources for people who are trying to figure out where to start, but they lack some of the tooling and optimizations of Emscripten.
The Emscripten tool is able to take just about any C/C++ source code and compile it into a Wasm module, plus the necessary JavaScript "glue" code for loading and running the module, and an HTML document to display the results of the code.

In a nutshell, the process works as follows:
1. Emscripten first feeds the C/C++ into clang+LLVM β a mature open-source C/C++ compiler toolchain, shipped as part of XCode on OSX for example.
2. Emscripten transforms the compiled result of clang+LLVM into a Wasm binary.
3. By itself, WebAssembly cannot currently directly access the DOM; it can only call JavaScript, passing in integer and floating point primitive data types. Thus, to access any Web API, WebAssembly needs to call out to JavaScript, which then makes the Web API call. Emscripten therefore creates the HTML and JavaScript glue code needed to achieve this.
> **Note:** There are future plans to [allow WebAssembly to call Web APIs directly](https://github.com/WebAssembly/gc/blob/master/README.md).
The JavaScript glue code is not as simple as you might imagine. For a start, Emscripten implements popular C/C++ libraries like [SDL](https://en.wikipedia.org/wiki/Simple_DirectMedia_Layer), [OpenGL](https://en.wikipedia.org/wiki/OpenGL), [OpenAL](https://en.wikipedia.org/wiki/OpenAL), and parts of [POSIX](https://en.wikipedia.org/wiki/POSIX). These libraries are implemented in terms of Web APIs and thus each one requires some JavaScript glue code to connect WebAssembly to the underlying Web API.
So part of the glue code is implementing the functionality of each respective library used by the C/C++ code. The glue code also contains the logic for calling the above-mentioned WebAssembly JavaScript APIs to fetch, load and run the Wasm file.
The generated HTML document loads the JavaScript glue file and writes stdout to a {{htmlelement("textarea")}}. If the application uses OpenGL, the HTML also contains a {{htmlelement("canvas")}} element that is used as the rendering target. It's very easy to modify the Emscripten output and turn it into whatever web app you require.
You can find full documentation on Emscripten at [emscripten.org](https://emscripten.org), and a guide to implementing the toolchain and compiling your own C/C++ app across to Wasm at [Compiling from C/C++ to WebAssembly](/en-US/docs/WebAssembly/C_to_Wasm).
### Writing WebAssembly directly
Do you want to build your own compiler, or your own tools, or make a JavaScript library that generates WebAssembly at runtime?
In the same fashion as physical assembly languages, the WebAssembly binary format has a text representation β the two have a 1:1 correspondence. You can write or generate this format by hand and then convert it into the binary format with any of several [WebAssembly text-to-binary tools](https://webassembly.org/getting-started/advanced-tools/).
For a simple guide on how to do this, see our [Converting WebAssembly text format to Wasm](/en-US/docs/WebAssembly/Text_format_to_Wasm) article.
### Writing Rust Targeting WebAssembly
It is also possible to write Rust code and compile over to WebAssembly, thanks to the tireless work of the Rust WebAssembly Working Group. You can get started with installing the necessary toolchain, compiling a sample Rust program to a WebAssembly npm package, and using that in a sample web app, over at our [Compiling from Rust to WebAssembly](/en-US/docs/WebAssembly/Rust_to_Wasm) article.
### Using AssemblyScript
For web developers who want to try WebAssembly without needing to learn the details of C or Rust, staying in the comfort of a familiar language like TypeScript, AssemblyScript will be the best option. AssemblyScript compiles a strict variant of TypeScript to WebAssembly, allowing web developers to keep using TypeScript-compatible tooling they are familiar with β such as Prettier, ESLint, VS Code IntelliSense, etc. You can check its documentation on <https://www.assemblyscript.org/>.
## Summary
This article has given you an explanation of what WebAssembly is, why it is so useful, how it fits into the web, and how you can make use of it.
## See also
- [WebAssembly articles on Mozilla Hacks blog](https://hacks.mozilla.org/category/webassembly/)
- [WebAssembly on Mozilla Research](https://research.mozilla.org/)
- [Loading and running WebAssembly code](/en-US/docs/WebAssembly/Loading_and_running) β find out how to load your own WebAssembly module into a web page.
- [Using the WebAssembly JavaScript API](/en-US/docs/WebAssembly/Using_the_JavaScript_API) β find out how to use the other major features of the WebAssembly JavaScript API.
| 0 |
data/mdn-content/files/en-us/webassembly | data/mdn-content/files/en-us/webassembly/using_the_javascript_api/index.md | ---
title: Using the WebAssembly JavaScript API
slug: WebAssembly/Using_the_JavaScript_API
page-type: guide
---
{{WebAssemblySidebar}}
If you have already [compiled a module from another language using tools like Emscripten](/en-US/docs/WebAssembly/C_to_Wasm), or [loaded and run the code yourself](/en-US/docs/WebAssembly/Loading_and_running), the next step is to learn more about using the other features of the WebAssembly JavaScript API. This article teaches you what you'll need to know.
> **Note:** If you are unfamiliar with the basic concepts mentioned in this article and need more explanation, read [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts) first, then come back.
## Some simple examples
Let's run through some examples that explain how to use the WebAssembly JavaScript API, and how to use it to load a Wasm module in a web page.
> **Note:** You can find the sample code in our [webassembly-examples](https://github.com/mdn/webassembly-examples) GitHub repo.
### Preparing the example
1. First we need a Wasm module! Grab our [`simple.wasm`](https://raw.githubusercontent.com/mdn/webassembly-examples/master/js-api-examples/simple.wasm) file and save a copy in a new directory on your local machine.
2. Next, let's create a simple HTML file called `index.html` in the same directory as your Wasm file (can use our [simple template](https://github.com/mdn/webassembly-examples/blob/main/template/template.html) if you haven't got one easily available).
3. Now, to help us understand what is going on here, let's look at the text representation of our Wasm module (which we also meet in [Converting WebAssembly format to Wasm](/en-US/docs/WebAssembly/Text_format_to_Wasm#a_first_look_at_the_text_format)):
```wasm
(module
(func $i (import "imports" "imported_func") (param i32))
(func (export "exported_func")
i32.const 42
call $i))
```
4. In the second line, you will see that the import has a two-level namespace β the internal function `$i` is imported from `imports.imported_func`. We need to reflect this two-level namespace in JavaScript when writing the object to be imported into the Wasm module. Create a `<script></script>` element in your HTML file, and add the following code to it:
```js
const importObject = {
imports: { imported_func: (arg) => console.log(arg) },
};
```
### Streaming the WebAssembly module
New in Firefox 58 is the ability to compile and instantiate WebAssembly modules directly from underlying sources. This is achieved using the [`WebAssembly.compileStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/compileStreaming_static) and [`WebAssembly.instantiateStreaming()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiateStreaming_static) methods. These methods are easier than their non-streaming counterparts, because they can turn the byte code directly into `Module`/`Instance` instances, cutting out the need to separately put the {{domxref("Response")}} into an {{jsxref("ArrayBuffer")}}.
This example (see our [instantiate-streaming.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/instantiate-streaming.html) demo on GitHub, and [view it live](https://mdn.github.io/webassembly-examples/js-api-examples/instantiate-streaming.html) also) shows how to use `instantiateStreaming()` to fetch a Wasm module, import a JavaScript function into it, compile and instantiate it, and access its exported function β all in one step.
Add the following to your script, below the first block:
```js
WebAssembly.instantiateStreaming(fetch("simple.wasm"), importObject).then(
(obj) => obj.instance.exports.exported_func(),
);
```
The net result of this is that we call our exported WebAssembly function `exported_func`, which in turn calls our imported JavaScript function `imported_func`, which logs the value provided inside the WebAssembly instance (42) to the console. If you save your example code now and load it a browser that supports WebAssembly, you'll see this in action!
> **Note:** This is a convoluted, long-winded example that achieves very little, but it does serve to illustrate what is possible β using WebAssembly code alongside JavaScript in your web applications. As we've said elsewhere, WebAssembly doesn't aim to replace JavaScript; the two instead can work together, drawing on each other's strengths.
### Loading our Wasm module without streaming
If you can't or don't want to use the streaming methods as described above, you can use the non-streaming methods [`WebAssembly.compile()`](/en-US/docs/WebAssembly/JavaScript_interface/compile_static) / [`WebAssembly.instantiate()`](/en-US/docs/WebAssembly/JavaScript_interface/instantiate_static) instead.
These methods don't directly access the byte code, so require an extra step to turn the response into an {{jsxref("ArrayBuffer")}} before compiling/instantiating the Wasm module.
The equivalent code would look like this:
```js
fetch("simple.wasm")
.then((response) => response.arrayBuffer())
.then((bytes) => WebAssembly.instantiate(bytes, importObject))
.then((results) => {
results.instance.exports.exported_func();
});
```
### Viewing Wasm in developer tools
In Firefox 54+, the Developer Tool Debugger Panel has functionality to expose the text representation of any Wasm code included in a web page. To view it, you can go to the Debugger Panel and click on the "wasm://" entry.

In addition to viewing WebAssembly as text, developers are able to debug (place breakpoints, inspect the callstack, single-step, etc.) WebAssembly using the text format.
## Memory
In the low-level memory model of WebAssembly, memory is represented as a contiguous range of untyped bytes called [Linear Memory](https://webassembly.github.io/spec/core/exec/index.html) that are read and written by [load and store instructions](https://webassembly.github.io/spec/core/exec/instructions.html#memory-instructions) inside the module. In this memory model, any load or store can access any byte in the entire linear memory, which is necessary to faithfully represent C/C++ concepts like pointers.
Unlike a native C/C++ program, however, where the available memory range spans the entire process, the memory accessible by a particular WebAssembly Instance is confined to one specific β potentially very small β range contained by a WebAssembly Memory object. This allows a single web app to use multiple independent libraries β each of which are using WebAssembly internally β to have separate memories that are fully isolated from each other. In addition, newer implementations can also create [shared memories](/en-US/docs/WebAssembly/Understanding_the_text_format#shared_memories), which can be transferred between Window and Worker contexts using [`postMessage()`](/en-US/docs/Web/API/Window/postMessage), and used in multiple places.
In JavaScript, a Memory instance can be thought of as a resizable [`ArrayBuffer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) (or [`SharedArrayBuffer`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), in the case of shared memories) and, just as with `ArrayBuffers`, a single web app can create many independent Memory objects. You can create one using the [`WebAssembly.Memory()`](/en-US/docs/WebAssembly/JavaScript_interface/Memory) constructor, which takes as arguments an initial size and (optionally) a maximum size and a `shared` property that states whether it is a shared memory or not.
Let's start exploring this by looking at a quick example.
1. Create another new simple HTML page (copy our [simple template](https://github.com/mdn/webassembly-examples/blob/main/template/template.html)) and call it `memory.html`. Add a `<script></script>` element to the page.
2. Now add the following line to the top of your script, to create a memory instance:
```js
const memory = new WebAssembly.Memory({ initial: 10, maximum: 100 });
```
The unit of `initial` and `maximum` is WebAssembly pages β these are fixed to 64KB in size. This means that the above memory instance has an initial size of 640KB, and a maximum size of 6.4MB.
WebAssembly memory exposes its bytes by providing a buffer getter/setter that returns an ArrayBuffer. For example, to write 42 directly into the first word of linear memory, you can do this:
```js
new Uint32Array(memory.buffer)[0] = 42;
```
You can then return the same value using:
```js
new Uint32Array(memory.buffer)[0];
```
3. Try this now in your demo β save what you've added so far, load it in your browser, then try entering the above two lines in your JavaScript console.
### Growing memory
A memory instance can be grown by calls to [`Memory.prototype.grow()`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/grow), where again the argument is specified in units of WebAssembly pages:
```js
memory.grow(1);
```
If a maximum value was supplied upon creation of the memory instance, attempts to grow past this maximum will throw a {{jsxref("RangeError")}} exception. The engine takes advantage of this supplied upper-bounds to reserve memory ahead of time, which can make resizing more efficient.
Note: Since an {{jsxref("ArrayBuffer")}}'s byteLength is immutable, after a successful [`Memory.prototype.grow()`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/grow) operation the buffer getter will return a new ArrayBuffer object (with the new byteLength) and any previous ArrayBuffer objects become "detached", or disconnected from the underlying memory they previously pointed to.
Just like functions, linear memories can be defined inside a module or imported. Similarly, a module may also optionally export its memory. This means that JavaScript can get access to the memory of a WebAssembly instance either by creating a new `WebAssembly.Memory` and passing it in as an import or by receiving a Memory export (via [`Instance.prototype.exports`](/en-US/docs/WebAssembly/JavaScript_interface/Instance/exports)).
### More involved memory example
Let's make the above assertions clearer by looking at a more involved memory example β a WebAssembly module that imports the memory instance we defined earlier, populates it with an array of integers, then sums them. You can find this at [memory.wasm.](https://raw.githubusercontent.com/mdn/webassembly-examples/master/js-api-examples/memory.wasm)
1. make a local copy of `memory.wasm` in the same directory as before.
> **Note:** You can see the module's text representation at [memory.wat](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/memory.wat).
2. Go back to your `memory.html` sample file, and fetch, compile, and instantiate your Wasm module as before β add the following to the bottom of your script:
```js
WebAssembly.instantiateStreaming(fetch("memory.wasm"), {
js: { mem: memory },
}).then((results) => {
// add code here
});
```
3. Since this module exports its memory, given an Instance of this module called instance we can use an exported function `accumulate()` to create and populate an input array directly in the module instance's linear memory (`mem`). Add the following into your code, where indicated:
```js
const i32 = new Uint32Array(memory.buffer);
for (let i = 0; i < 10; i++) {
i32[i] = i;
}
const sum = results.instance.exports.accumulate(0, 10);
console.log(sum);
```
Note how we create the {{jsxref("Uint32Array")}} view on the Memory object's buffer ([`Memory.prototype.buffer`](/en-US/docs/WebAssembly/JavaScript_interface/Memory/buffer)), not on the Memory itself.
Memory imports work just like function imports, only Memory objects are passed as values instead of JavaScript functions. Memory imports are useful for two reasons:
- They allow JavaScript to fetch and create the initial contents of memory before or concurrently with module compilation.
- They allow a single Memory object to be imported by multiple module instances, which is a critical building block for implementing dynamic linking in WebAssembly.
> **Note:** You can find our complete demo at [memory.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/memory.html) ([see it live also](https://mdn.github.io/webassembly-examples/js-api-examples/memory.html)) .
## Tables
A WebAssembly Table is a resizable typed array of [references](<https://en.wikipedia.org/wiki/Reference_(computer_science)>) that can be accessed by both JavaScript and WebAssembly code. While Memory provides a resizable typed array of raw bytes, it is unsafe for references to be stored in a Memory since a reference is an engine-trusted value whose bytes must not be read or written directly by content for safety, portability, and stability reasons.
Tables have an element type, which limits the types of reference that can be stored in the table. In the current iteration of WebAssembly, there is only one type of reference needed by WebAssembly code β functions β and thus only one valid element type. In future iterations, more element types will be added.
Function references are necessary to compile languages like C/C++ that have function pointers. In a native implementation of C/C++, a function pointer is represented by the raw address of the function's code in the process's virtual address space and so, for the safety reasons mentioned above, cannot be stored directly in linear memory. Instead, function references are stored in a table and their indexes, which are integers and can be stored in linear memory, are passed around instead.
When the time comes to call a function pointer, the WebAssembly caller supplies the index, which can then be safety bounds checked against the table before indexing and calling the indexed function reference. Thus, tables are currently a rather low-level primitive used to compile low-level programming language features safely and portably.
Tables can be mutated via [`Table.prototype.set()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/set), which updates one of the values in a table, and [`Table.prototype.grow()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/grow), which increases the number of values that can be stored in a table. This allows the indirectly-callable set of functions to change over time, which is necessary for [dynamic linking techniques](https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md). The mutations are immediately accessible via [`Table.prototype.get()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/get) in JavaScript, and to Wasm modules.
### A table example
Let's look at a simple table example β a WebAssembly module that creates and exports a table with two elements: element 0 returns 13 and element 1 returns 42. You can find this at [table.wasm](https://raw.githubusercontent.com/mdn/webassembly-examples/master/js-api-examples/table.wasm).
1. Make a local copy of `table.wasm` in a new directory.
> **Note:** You can see the module's text representation at [table.wat](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/table.wat).
2. Create a new copy of our [HTML template](https://github.com/mdn/webassembly-examples/blob/main/template/template.html) in the same directory and call it `table.html`.
3. As before, fetch, compile, and instantiate your Wasm module β add the following into a {{htmlelement("script")}} element at the bottom of your HTML body:
```js
WebAssembly.instantiateStreaming(fetch("table.wasm")).then((results) => {
// add code here
});
```
4. Now let's access the data in the tables β add the following lines to your code in the indicated place:
```js
const tbl = results.instance.exports.tbl;
console.log(tbl.get(0)()); // 13
console.log(tbl.get(1)()); // 42
```
This code accesses each function reference stored in the table in turn, and instantiates them to print the values they hold to the console β note how each function reference is retrieved with a [`Table.prototype.get()`](/en-US/docs/WebAssembly/JavaScript_interface/Table/get) call, then we add an extra set of parentheses on the end to actually invoke the function.
> **Note:** You can find our complete demo at [table.html](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/table.html) ([see it live also](https://mdn.github.io/webassembly-examples/js-api-examples/table.html)).
## Globals
WebAssembly has the ability to create global variable instances, accessible from both JavaScript and importable/exportable across one or more [`WebAssembly.Module`](/en-US/docs/WebAssembly/JavaScript_interface/Module) instances. This is very useful, as it allows dynamic linking of multiple modules.
To create a WebAssembly global instance from inside your JavaScript, you use the [`WebAssembly.Global()`](/en-US/docs/WebAssembly/JavaScript_interface/Global) constructor, which looks like this:
```js
const global = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
```
You can see that this takes two parameters:
- An object that contains two properties describing the global variable:
- `value`: its data type, which can be any data type accepted within WebAssembly modules β `i32`, `i64`, `f32`, or `f64`.
- `mutable`: a boolean defining whether the value is mutable or not.
- A value containing the variable's actual value. This can be any value, as long as its type matches the specified data type.
So how do we use this? In the following example we define a global as a mutable `i32` type, with a value of 0.
The value of the global is then changed, first to `42` using the `Global.value` property, and then to 43 using the `incGlobal()` function exported out of the `global.wasm` module (this adds 1 to whatever value is given to it and then returns the new value).
```js
const output = document.getElementById("output");
function assertEq(msg, got, expected) {
const result =
got === expected
? `SUCCESS! Got: ${got}<br>`
: `FAIL!<br>Got: ${got}<br>Expected: ${expected}<br>`;
output.innerHTML += `Testing ${msg}: ${result}`;
}
assertEq("WebAssembly.Global exists", typeof WebAssembly.Global, "function");
const global = new WebAssembly.Global({ value: "i32", mutable: true }, 0);
WebAssembly.instantiateStreaming(fetch("global.wasm"), { js: { global } }).then(
({ instance }) => {
assertEq(
"getting initial value from wasm",
instance.exports.getGlobal(),
0,
);
global.value = 42;
assertEq(
"getting JS-updated value from wasm",
instance.exports.getGlobal(),
42,
);
instance.exports.incGlobal();
assertEq("getting wasm-updated value from JS", global.value, 43);
},
);
```
> **Note:** You can see the example [running live on GitHub](https://mdn.github.io/webassembly-examples/js-api-examples/global.html); see also the [source code](https://github.com/mdn/webassembly-examples/blob/main/js-api-examples/global.html).
## Multiplicity
Now we've demonstrated usage of the main key WebAssembly building blocks, this is a good place to mention the concept of multiplicity. This provides WebAssembly with a multitude of advances in terms of architectural efficiency:
- One module can have N Instances, in the same way that one function literal can produce N closure values.
- One module instance can use 0β1 memory instances, which provide the "address space" of the instance. Future versions of WebAssembly may allow 0βN memory instances per module instance (see [Multiple Memories](https://webassembly.org/roadmap/)).
- One module instance can use 0β1 table instances β this is the "function address space" of the instance, used to implement C function pointers. Future versions of WebAssembly may allow 0βN table instances per module instance.
- One memory or table instance can be used by 0βN module instances β these instances all share the same address space, allowing [dynamic linking](https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md).
You can see multiplicity in action in our Understanding text format article β see the [Mutating tables and dynamic linking section](/en-US/docs/WebAssembly/Understanding_the_text_format#mutating_tables_and_dynamic_linking).
## Summary
This article has taken you through the basics of using the WebAssembly JavaScript API to include a WebAssembly module in a JavaScript context and make use of its functions, and how to use WebAssembly memory and tables in JavaScript. We also touched on the concept of multiplicity.
## See also
- [webassembly.org](https://webassembly.org/)
- [WebAssembly concepts](/en-US/docs/WebAssembly/Concepts)
- [WebAssembly on Mozilla Research](https://research.mozilla.org/)
| 0 |
data/mdn-content/files/en-us/webassembly | data/mdn-content/files/en-us/webassembly/reference/index.md | ---
title: WebAssembly instruction reference
slug: WebAssembly/Reference
page-type: landing-page
---
{{WebAssemblySidebar}}
- [`Numeric instructions`](/en-US/docs/WebAssembly/Reference/Numeric)
- [`Vector/SIMD instructions`](/en-US/docs/WebAssembly/Reference/Vector)
- [`Reference instructions`](/en-US/docs/WebAssembly/Reference/Reference)
- [`Variable instructions`](/en-US/docs/WebAssembly/Reference/Variables)
- [`Table instructions`](/en-US/docs/WebAssembly/Reference/Table)
- [`Memory instructions`](/en-US/docs/WebAssembly/Reference/Memory)
- [`Control flow instructions`](/en-US/docs/WebAssembly/Reference/Control_flow)
| 0 |
data/mdn-content/files/en-us/webassembly/reference | data/mdn-content/files/en-us/webassembly/reference/control_flow/index.md | ---
title: WebAssembly control flow instructions
slug: WebAssembly/Reference/Control_flow
page-type: landing-page
---
{{WebAssemblySidebar}}
WebAssembly control flow instructions.
- [`block`](/en-US/docs/WebAssembly/Reference/Control_flow/block)
- : Creates a label that can later be branched out of with a [`br`](/en-US/docs/WebAssembly/Reference/Control_flow/br).
- [`br`](/en-US/docs/WebAssembly/Reference/Control_flow/br)
- : Branches to a loop or block.
- [`call`](/en-US/docs/WebAssembly/Reference/Control_flow/call)
- : Calls a function.
- [`drop`](/en-US/docs/WebAssembly/Reference/Control_flow/Drop)
- : Pops a value from the stack, and discards it.
- [`end`](/en-US/docs/WebAssembly/Reference/Control_flow/end)
- : Can be used to end a `block`, `loop`, `if`, or `else`.
- [`if...else`](/en-US/docs/WebAssembly/Reference/Control_flow/if...else)
- : Executes a statement if the last item on the stack is true (`1`).
- [`loop`](/en-US/docs/WebAssembly/Reference/Control_flow/loop)
- : Creates a label that can later be branched to with a [`br`](/en-US/docs/WebAssembly/Reference/Control_flow/br).
- [`nop`](/en-US/docs/WebAssembly/Reference/Control_flow/nop)
- : Does nothing.
- [`return`](/en-US/docs/WebAssembly/Reference/Control_flow/return)
- : Returns from a function.
- [`select`](/en-US/docs/WebAssembly/Reference/Control_flow/Select)
- : Selects one of its first two operands based on a boolean condition.
- [`unreachable`](/en-US/docs/WebAssembly/Reference/Control_flow/unreachable)
- : Denotes a point in code that should not be reachable.
| 0 |
data/mdn-content/files/en-us/webassembly/reference/control_flow | data/mdn-content/files/en-us/webassembly/reference/control_flow/br/index.md | ---
title: br
slug: WebAssembly/Reference/Control_flow/br
page-type: webassembly-instruction
---
{{WebAssemblySidebar}}
The **`br`** statement branches to a loop, block, or if.
Other variants of `br` are `br_if` for branching on condition, and `br_table` for branching to different blocks based on an argument.
{{EmbedInteractiveExample("pages/wat/br.html", "tabbed-taller")}}
## Syntax
```wasm
;; label the loop so that it can be branched to
(loop $my_loop
;; branch to the loop.
;; most of the time you'll want to put this in an if statement and only branch on condition,
;; otherwise you have an infinite loop.
br $my_loop
)
```
| Instruction | Binary opcode |
| ----------- | ------------- |
| `br` | `0x0c` |
| `br_if` | `0x0d` |
| `br_table` | `0x0e` |
| 0 |
data/mdn-content/files/en-us/webassembly/reference/control_flow | data/mdn-content/files/en-us/webassembly/reference/control_flow/return/index.md | ---
title: return
slug: WebAssembly/Reference/Control_flow/return
page-type: webassembly-instruction
---
{{WebAssemblySidebar}}
**`return`** returns from a function.
- If there are no values left on the stack, it returns nothing/void.
- If there are the same amount of values left on the stack as specified in the function's type signature, it returns those values.
- If there are more values that the function's return type specifies, then the excess values are popped from the stack and discarded, and the last N values are returned.
{{EmbedInteractiveExample("pages/wat/return.html", "tabbed-taller")}}
## Syntax
```wasm
f32.const 4.3
return
```
```wasm
i32.const 7
f32.const 4.3
return
```
| Instruction | Binary opcode |
| ----------- | ------------- |
| `return` | `0x0f` |
| 0 |
data/mdn-content/files/en-us/webassembly/reference/control_flow | data/mdn-content/files/en-us/webassembly/reference/control_flow/call/index.md | ---
title: call
slug: WebAssembly/Reference/Control_flow/call
page-type: webassembly-instruction
---
{{WebAssemblySidebar}}
**`call`** calls a function, `return_call` being the tail-call version of it. `call_indirect` calls a function in a table with the `return_call_indirect` tail-call version as well.
{{EmbedInteractiveExample("pages/wat/call.html", "tabbed-standard")}}
## Syntax
```wasm
call $greet
```
| Instruction | Binary opcode |
| ---------------------- | ------------- |
| `call` | `0x10` |
| `call_indirect` | `0x11` |
| `return_call` | `0x12` |
| `return_call_indirect` | `0x13` |
## See also
- [Tail Call Extension proposal overview](https://github.com/WebAssembly/tail-call/blob/main/proposals/tail-call/Overview.md)
- [V8 on WebAssembly tail calls support](https://v8.dev/blog/wasm-tail-call)
| 0 |
data/mdn-content/files/en-us/webassembly/reference/control_flow | data/mdn-content/files/en-us/webassembly/reference/control_flow/select/index.md | ---
title: Select
slug: WebAssembly/Reference/Control_flow/Select
page-type: webassembly-instruction
---
{{WebAssemblySidebar}}
The **`select`** instruction, selects one of its first two operands based on whether its third operand is zero or not. It shares some similarities with the ternary operator in other languages (e.g. `false ? 10 : 20`), but doesn't [short-circuit](https://en.wikipedia.org/wiki/Short-circuit_evaluation). The instruction may be followed by an immediate value type: `select (result T)`. `select (result T)` uses a different binary opcode, and allows types besides those introduced by the WebAssembly MVP (`i32`, `i64`, `f32`, `f64`), for example, it allows selection between two `externref` values.
{{EmbedInteractiveExample("pages/wat/select.html", "tabbed-taller")}}
## Syntax
```wasm
;; push two values onto the stack
i32.const 10
i32.const 20
;; change to `1` (true) to get the first value (`10`)
i32.const 0
select
```
```plain
f32.const nan
f32.const -54.1
;; change to `1` (true) to get the first value (`nan`)
i32.const 0
select (result f32)
```
| Instruction | Binary opcode |
| ----------- | ------------- |
| `select` | `0x1b` |
| `select t` | `0x1c` |
| 0 |
data/mdn-content/files/en-us/webassembly/reference/control_flow | data/mdn-content/files/en-us/webassembly/reference/control_flow/nop/index.md | ---
title: nop
slug: WebAssembly/Reference/Control_flow/nop
page-type: webassembly-instruction
---
{{WebAssemblySidebar}}
**`nop`** stands for no-operation. It literally does nothing.
{{EmbedInteractiveExample("pages/wat/nop.html", "tabbed-shorter")}}
## Syntax
```wasm
nop
```
| Instruction | Binary opcode |
| ----------- | ------------- |
| `nop` | `0x01` |
| 0 |
data/mdn-content/files/en-us/webassembly/reference/control_flow | data/mdn-content/files/en-us/webassembly/reference/control_flow/loop/index.md | ---
title: loop
slug: WebAssembly/Reference/Control_flow/loop
page-type: webassembly-instruction
---
{{WebAssemblySidebar}}
The **`loop`** statement creates a label that can later be branched to with a `br`. The loop instruction doesn't loop by itself; you need to branch to it to actually create a loop.
The **`loop`** statement is the opposite of the `block` statement, in the sense that while branching to a `loop` jumps to the beginning of the loop, branching to a `block` jumps to the end of the block, that is, out of the block.
{{EmbedInteractiveExample("pages/wat/loop.html", "tabbed-taller")}}
## Syntax
```wasm
;; label the loop so that it can be branched to
(loop $my_loop
;; branch to the loop.
;; most of the time you'll want to put this in an if statement and only branch on condition,
;; otherwise you have an infinite loop.
br $my_loop
)
```
| Instruction | Binary opcode |
| ----------- | ------------- |
| `loop` | `0x03` |
| 0 |
data/mdn-content/files/en-us/webassembly/reference/control_flow | data/mdn-content/files/en-us/webassembly/reference/control_flow/end/index.md | ---
title: end
slug: WebAssembly/Reference/Control_flow/end
page-type: webassembly-instruction
---
{{WebAssemblySidebar}}
**`end`** is used to end a `block`, `loop`, `if`, or `else`. In the other examples we used the s-expression syntax which doesn't require the `end`, so you won't find it in the other examples here. However, it's still useful to know about since this is what the browsers display in devtools.
{{EmbedInteractiveExample("pages/wat/end.html", "tabbed-taller")}}
## Syntax
```wasm
i32.const 0
if
;; do something
end
```
| Instruction | Binary opcode |
| ----------- | ------------- |
| `end` | `0x0b` |
| 0 |
data/mdn-content/files/en-us/webassembly/reference/control_flow | data/mdn-content/files/en-us/webassembly/reference/control_flow/unreachable/index.md | ---
title: unreachable
slug: WebAssembly/Reference/Control_flow/unreachable
page-type: webassembly-instruction
---
{{WebAssemblySidebar}}
**`unreachable`** is used to denote a point in code that should not be reachable. `unreachable` is an unconditional trap: in the case where an `unreachable` is reached and executed, the instruction traps.
{{EmbedInteractiveExample("pages/wat/unreachable.html", "tabbed-shorter")}}
## Syntax
```wasm
unreachable
```
| Instruction | Binary opcode |
| ------------- | ------------- |
| `unreachable` | `0x00` |
| 0 |
data/mdn-content/files/en-us/webassembly/reference/control_flow | data/mdn-content/files/en-us/webassembly/reference/control_flow/if...else/index.md | ---
title: if...else
slug: WebAssembly/Reference/Control_flow/if...else
page-type: webassembly-instruction
---
{{WebAssemblySidebar}}
The **`if`** statement executes a statement if the last item on the stack is true (1). If the condition is false (0), another statement can be executed
{{EmbedInteractiveExample("pages/wat/if...else.html", "tabbed-taller")}}
## Syntax
```wasm
i32.const 0
(if
(then
;; do something
)
(else
;; do something else
)
)
```
| Instruction | Binary opcode |
| ----------- | ------------- |
| `if` | `0x04` |
| `else` | `0x05` |
| 0 |
data/mdn-content/files/en-us/webassembly/reference/control_flow | data/mdn-content/files/en-us/webassembly/reference/control_flow/drop/index.md | ---
title: Drop
slug: WebAssembly/Reference/Control_flow/Drop
page-type: webassembly-instruction
---
{{WebAssemblySidebar}}
The **`drop`** instruction, pops a value from the stack, and discards it.
{{EmbedInteractiveExample("pages/wat/drop.html", "tabbed-taller")}}
## Syntax
```wasm
;; push multiple values onto the stack
i32.const 1
i32.const 2
i32.const 3
;; drop the top item from the stack (`3`)
drop
;; the top item on the stack will now be `2`
```
| Instruction | Binary opcode |
| ----------- | ------------- |
| `drop` | `0x1a` |
| 0 |
data/mdn-content/files/en-us/webassembly/reference/control_flow | data/mdn-content/files/en-us/webassembly/reference/control_flow/block/index.md | ---
title: block
slug: WebAssembly/Reference/Control_flow/block
page-type: webassembly-instruction
---
{{WebAssemblySidebar}}
The **`block`** statement creates a label that can later be branched out of with a `br`.
The **`loop`** statement is the opposite of the `block` statement, in the sense that while branching to a `loop` jumps to the beginning of the loop, branching to a `block` jumps to the end of the block; that is, out of the block.
{{EmbedInteractiveExample("pages/wat/block.html", "tabbed-taller")}}
## Syntax
```wasm
;; label the block so that it can be branched to.
(block $my_block
;; branch to the block.
;; most of the time you'll want to put this in an if statement and only branch on condition,
;; otherwise the following control flow are unreachable.
br $my_block
;; this will never be reached, since the br jumped out of the block already.
unreachable
)
```
| Instruction | Binary opcode |
| ----------- | ------------- |
| `block` | `0x02` |
| 0 |
data/mdn-content/files/en-us/webassembly/reference | data/mdn-content/files/en-us/webassembly/reference/memory/index.md | ---
title: WebAssembly memory instructions
slug: WebAssembly/Reference/Memory
page-type: landing-page
---
{{WebAssemblySidebar}}
WebAssembly memory instructions.
- [`Grow`](/en-US/docs/WebAssembly/Reference/Memory/Grow)
- : Increase the size of the memory instance.
- [`Size`](/en-US/docs/WebAssembly/Reference/Memory/Size)
- : Get the size of the memory instance.
- [`Load`](/en-US/docs/WebAssembly/Reference/Memory/Load)
- : Load a number from memory.
- [`Store`](/en-US/docs/WebAssembly/Reference/Memory/Store)
- : Store a number in memory.
- [`Copy`](/en-US/docs/WebAssembly/Reference/Memory/Copy)
- : Copy data from one region in memory to another
- [`Fill`](/en-US/docs/WebAssembly/Reference/Memory/Fill)
- : Set all values in a region to a specific byte
| 0 |
data/mdn-content/files/en-us/webassembly/reference/memory | data/mdn-content/files/en-us/webassembly/reference/memory/store/index.md | ---
title: Store
slug: WebAssembly/Reference/Memory/Store
page-type: webassembly-instruction
---
{{WebAssemblySidebar}}
The **`store`** instructions, are used to store a number in memory.
For the integer numbers, you can also store a wide typed number as a narrower number in memory, e.g. store a 32-bit number in an 8-bit slot (**`i32.store8`**). If the number doesn't fit in the narrower number type it will wrap.
{{EmbedInteractiveExample("pages/wat/store.html", "tabbed-taller")}}
## Syntax
```wasm
;; the offset in memory where to store the number
i32.const 0
;; the number to store
i32.const 20
;; store 20 at position 0
i32.store
```
| Instruction | Binary opcode |
| ------------- | ------------- |
| `i32.store` | `0x36` |
| `i64.store` | `0x37` |
| `f32.store` | `0x38` |
| `f64.store` | `0x39` |
| `i32.store8` | `0x3a` |
| `i32.store16` | `0x3b` |
| `i64.store8` | `0x3c` |
| `i64.store16` | `0x3d` |
| `i64.store32` | `0x3e` |
| 0 |
data/mdn-content/files/en-us/webassembly/reference/memory | data/mdn-content/files/en-us/webassembly/reference/memory/grow/index.md | ---
title: Grow
slug: WebAssembly/Reference/Memory/Grow
page-type: webassembly-instruction
---
{{WebAssemblySidebar}}
The **`grow`** instruction, increases the size of the memory instance by a specified number of pages, each page is sized 64KiB.
The **`grow`** instruction returns previous size of memory, in pages, if the operation was successful, and returns **`-1`** if the operation failed.
{{EmbedInteractiveExample("pages/wat/grow.html", "tabbed-taller")}}
## Syntax
```wasm
;; load the number of memory pages to grow the memory by
i32.const 3
;; grow the memory by 3 pages
memory.grow
;; the top item on the stack will now either be the previous number of pages (success) or `-1` (failure)
```
| Instruction | Binary opcode |
| ------------- | ------------- |
| `memory.grow` | `0x40` |
| 0 |
Subsets and Splits