How to create and run your first Svelte Rollup Application?
Tags: javascript, svelte, webdev
Published: 2022-01-17 06:35:02

In this post, we will learn how to run our first Svelte Rollup Application.

To make things easy to understand, we will create a small Svelte app from scratch and write a basic **Rollup** configuration to build and run the application.

But before that, let's go through some basics about Svelte.

### 1 – What is Svelte? 

Svelte is a new front-end **library**. It is known for its blazing fast speed. Unlike other UI libraries such as React, **Svelte is more of a compiler**. While traditional frameworks like  [React](https://progressivewebninja.com/create-react-app-the-fastest-way-to-start-a-new-react-project/)  or Vue do much of the work in the browser, Svelte shifts that work into the compile step.

Basically, browsers do not directly execute Svelte code. When we write Svelte code, **we need to have a build step that translates that code into standard HTML, CSS & Javascript**. This makes it faster while also transferring less code to the browser when the user makes a request.

### 2 – Setting up a new Svelte Project

To demo our **Svelte Rollup application**, we will create an extremely simple Svelte application. To achieve it, we have to first setup our project.

First, we will create a new directory to place our application files.

```bash
$ mkdir my-first-svelte-app
```

Next, we navigate into the directory and then initialize a new **npm** project.

```bash
$ cd my-first-svelte-app
$ npm init -y
```

The above commands will generate a `package.json` file for our application. Now we can install the required packages. As a first step, we install the `svelte` package.

```bash
$ npm install svelte
```

After the installation is completed, we are ready to write some code for our demo application.

### 3 – Creating the Svelte App

By convention, we put all our code into the `src` directory. You can use any editor of your choice or the terminal to create the same. Inside the `src` directory, we create two files `App.svelte` and `main.js`.

The `App.svelte` file will contain the actual component code as below:

#### **`App.svelte`**
```html
<script>
    export let name;
</script>

<p>Hello {name}</p>
```

A very simple component indeed! We only have a paragraph that displays a hello message. The `name` within curly braces is a prop for the `App` component.

Next, we configure the `main.js` file as below:

#### **`main.js`**
```js
import App from './App.svelte';

const app = new App({
    target: document.body,
    props: {
        name: 'Web Ninja'
    },
});

export default app;
```

Here, we create a new instance of the `App` component. We also specify that we want to load the component in the document `body`. Lastly, we supply the `name` as part of the props object.

With this our Svelte application is ready. Time to delve into **how to actually run the application**.

### 4 – Installing Svelte Rollup Packages

As discussed earlier, we will be using Rollup to build and run our application.

***But what exactly is Rollup?***

**Rollup** is basically a **module bundler for Javascript applications**. It takes our application code and bundles it into files that browsers can easily parse. In other words, **Rollup converts our `.svelte` files into browser-understandable HTML, CSS and Javascript**.

To get started with Rollup, we first need to install the required package.

```bash
$ npm install -D rollup
```

Please note that this is a **development** dependency.

Next, we also need to install two more Rollup development dependencies. See below:

```bash
$ npm install -D @rollup/plugin-node-resolve rollup-plugin-svelte
```

The `@rollup/plugin-node-resolve` package **helps Rollup resolve any third party plugins**. The second dependency `rollup-plugin-svelte` is a **third party plugin** that helps Rollup understand how to handle Svelte applications.

As with `rollup`, both of these dependencies are also development only.

### 5 – Rollup Configuration File

Rollup also requires a configuration file to understand what it needs to do with our source code.

We will start by creating a very simple Rollup configuration file. It will simply bundle our Svelte application file into the `public/build` folder.

See below:

#### **`rollup.config.js`**
```js
import svelte from "rollup-plugin-svelte";
import resolve from '@rollup/plugin-node-resolve';

export default {
    input: 'src/main.js',
    output: {
        file: 'public/build/bundle.js',
        format: 'iife',
        name: 'app',
    },
    plugins: [
        svelte({
            include: 'src/**/*.svelte',
        }),
        resolve({ browser: true }),
    ],
}
```

Let us understand what we are doing here.

- In line 1 & 2, we have the necessary imports.
- In line 5, we specify the path to the input file. This is the `main.js` file of our application where instantiate our component.
- In line 6, we specify the `output`. Basically, this is the destination of our built artifacts. We also specify the format as `iife` (**immediately invoked function express**). Along with this, we specify the name of the variable to which we assign the `iife` output value. In this case, we name the variable as `app`.
- Lastly, from line 11 onwards, we specify the other configuration items. Basically, we tell Rollup the path to our `.svelte` files. Also, we indicate that we are building our application to work on a browser.

### 6 – Adding Rollup to NPM Script

The next step is to add Rollup to our NPM scripts so that we can build and run our application.

To run Rollup, we add a new script to our `package.json` file.

#### **`package.json`**
```json
"scripts": {
    "dev": "rollup -c -w",
}
```

The `-c` flag specifies that we want Rollup to use a configuration file. By default, it checks for a file named `rollup.config.js`. We already created the file in the previous section.

The `-w` flag instructs Rollup to watch our files for changes. In case we make changes to our source code, Rollup will automatically rebuilds the artifacts.

We can now run `npm run dev` to build our Svelte application. The built files will be placed inside `/public/build` folder.

### 7 – Serving the Content

Though we have successfully compiled our application, we still need a way to serve it. Therefore, we create an `index.html` file in the public folder.

#### **`index.html`**
```html
<html>
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>My First Svelte App</title>
        <script defer src="build/bundle.js"></script>
    </head>
    <body></body>
</html>
```

Important thing to note is the `script` tag where we specify the location to our newly built `bundle.js` file.

To serve the application, we will install a simple web server available with the `sirv-cli` package.

```bash
$ npm install -D sirv-cli
```

Finally, we add a script to run the application.

#### **`package.json`**
```json
"scripts": {
    "dev": "rollup -c -w",
    "start": "sirv public"
},
```

We can now start our application by running the command `npm run start`. The application will be accessible on `http://localhost:5000`. You should see the *hello message* in the browser window.

### Conclusion

With this, we have successfully learnt how to create and run a **Svelte Rollup application**. We created a new **Svelte** app from scratch and also wrote a basic Rollup configuration.

The code for this post is available on  [Github](https://github.com/dashsaurabh/svelte-rollup-demo) .

In the next post, we will look at how to configure  [Svelte Rollup Hot-Reload feature](https://progressivewebninja.com/how-to-configure-svelte-rollup-server-hot-reload/) so that we can improve the development experience.

If you have any comments or queries, please feel free to mention them in the comments section below.