Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
February 4, 2021 06:09 pm GMT

Building Web Apps With Svelte

Good day guys, in this article we will focus on using svelte.js to build user interfaces and web apps. Svelte.js is kinda a new kid on the block compared to other frameworks and libraries out there that you can use to build front-end projects, but that does not mean it offers, less. We will see how we can setup a basic sveltejs project and then we will delve into some of the basic svelte syntax and by the end of this article you will feel confident enough to go on to more advanced svelte concept.

What is Svelte

Svelte is a JavaScript compiler that is used to build dynamic and interactive web app and user interface, this statement implies that svelte will compile our code down into a JavaScript implementation when we build for production. This is unlike regular frameworks and libraries where the core library is also shipped together with our code. This is a good thing because apps built with svelte are much smaller in bundle size compared to apps built with other traditional frameworks. The svelte syntax is also very easy to learn, short and simple, logic that would take a 10 to 15 lines of code on other traditional frameworks will only take a few say, 5 to 6 lines of svelte code to achieve the same purpose, although it's syntax shares a few similarities with react, so if you have experience working with react then learning svelte will be easier, (History of svelte)

Installing Svelte

To install svelte on your computer you need to make sure that you have nodejs installed on your computer, open up an command terminal and type node -v and press enter that should throw off the version of nodejs you have installed on your computer if there is one, however if not then head to the node js webiste to download the latest version of nodejs. Once you've done that the next thing is to install a package from npm called degit. To do this type npm i degit -g in a command line and hit enter. This installs degit for us, degit makes cloning a git repo very easy and it is going to help us clone the svelte template from the svelte repo. Once degit has been installed we now need to clone the starter template from the svelte repo. In the command line type degit sveltejs/template svelte-app and hit enter. This command goes out to the svelte repo and clones the svelte template app to our pc and stores it inside a folder called svelte-app and you dont have to call it svelte-app, you can name it whatever you want. Just know that what ever name you pass to command, a folder will be created with that name and the content of the svelte starter template is going to be stored inside it. Once it has finished downloading, enter cd svelte-app in the command line and press enter, this and open up this folder in your text editor, if you have vs code installed on you pc type code . and it will open it automatically inside the svelte-app folder and press enter from the command line and this should open up the folder in vs code. Next thing is to install the dependencies because when we clone the repo it doesnt ship with it the svelte compiler and other modules svelte depends on so make sure you are inside the svelte-app folder inside the command line then hit npm install and press enter, grab a cup of smoothie and wait for that to finish loading up, and once that is done you should see a directory structure that looks like this

-------------------/node_modules                            |    |------------/src/            |    |------------/scripts/    |    |------------README.md    |    |------------/rollup.config.js
Enter fullscreen mode Exit fullscreen mode
  • The node modules folder contains the svelte library and other modules that svelte depends on.
  • We will talk about the src folder shortly
  • The README.md file contains useful information about running the app and i suggest that you go through it.
  • The rollup.config.js file is just a module budler much like webpack.

This is our basic folder structure right now, lets examine the src folder and check up it's content.

src/------------------------------/App.svelte            |            |------------/main.js
Enter fullscreen mode Exit fullscreen mode

The src folder contains two files,

  • App.svelte
  • main.js

The App.svelte is a svelte component that comes with the basic svelte template, note the .svelte extension. All our svelte components must end with the .svelte extension so that svelte compiler can process that file. The main.js file is a file that kick starts our svelte app, it imports the App component from the App.svelte file and initializes the component targeting document.body i.e all our app content will be injected to the document's body tag. It is inside this src folder that we write all our code, create our svelte components and all the rest.

The public folder is what is served to the browser when we are in development mode and it contains an index.html file, a global.css file that contains css rules that can be used to style our svelte components, the rules in this global.css is not scoped so it will have effect on all our svelte components, if we apply any class name contained in it to our components. We can also store other stylesheets, fonts, icons, images and other assets that our app depends in the public folder.

The script folder contains a setupTypeScript.js file that will enable us to use TypeScript in our svelte components. Now we have a basic knowledge of our file structure the next thing is to serve up the app and see the basic contents, to do that from your terminal, make sure you are at the root level in the svelte-app folder and then hit npm run dev and enter, this spins up a local development server with live reload feature, open up browser and navigate to 'localhost:5000' and you should see the starter template app that svelte comes baked with. Back to our editor and let's get our hands dirty and write some code, open up the App.svelte component and clear up the contents so that you have a blank file, type the following information into the file;

<script>    let hero = 'spiderman'</script><main>    <h2> { hero } </h2></main><style>    h2{        color: grey;    }</style>
Enter fullscreen mode Exit fullscreen mode

Save up the file and open your browser, you should see a gray colored text with the content 'spiderman'. If you have worked with Vue.js before you will notice that is similar to vue syntax. So the above code is basic svelte syntax, we have a script tag where we write JavaScript, and in this example we declared a variable called hero and set it equal to 'spiderman'. Next we have a main tag that has an h2 tag as it's child, we then use curly braces to dynamically inject the value of the hero variable we declared in the script tag as the content of the h2 tag. Lastly we have a style tag for adding styles to our components, the styles are scoped by default. Most of our svelte components will have these three basic tags; a script tag, a main tag(although you can use a div tag or any wrapper Html tag you like), and a style tag. You will agree with me that this is much simpler to understand and is easier to write than you would have using other front-end frameworks, e.g Angular, react or even Vue. That is the basic dynamic content injection, let's look at conditional rendering

Conditional Rendering

open up the app.svelte file and add the following contents to it;

<script>    let hero = 'spiderman'    let villain = 'Thanos'    let showHero = false    let showVillain = true</script><main>    {#if showHero}        <h2>{ hero }</h2>    {/if}    {#if showVillain}        <h2>{ villain }</h2>    {/if}</main><style>    h2{        color: grey;    }</style>
Enter fullscreen mode Exit fullscreen mode

Open up your browser and view the results, we see that Thanos is added to the DOM while spiderman is removed from it, because showHero is false and showVillain is true, anytime we want to do some conditional rendering we use a curly braces, and then use the # symbol followed immediately by the if keyword and then a condition we want to evaluate, then we close up the if block by using another curly braces and inside it we use the forward slash followed immediately by the if keyword. In between both we write the html template we want to be rendered to the DOM, depending on the result of our expression, our template will or not be rendered, if the condition evaluates to false, it wont be added to the DOM, if it evaluates to true i will be. In this instance we used two if blocks let's see how we can add an else statement to each of the if block. Make the following alterations to your code

<script>    let hero = 'spiderman'    let villain = 'Thanos'    let showHero = false    let showVillain = true</script><main>    {#if showHero}        <h2>{ hero }</h2>    {:else}        <h2>No hero yet</h2>    {/if}    {#if showVillain}        <h2>{ villain }</h2>    {:else}        <h2>No Villain yet</h2>    {/if}</main><style>    h2{        color: grey;    }</style>
Enter fullscreen mode Exit fullscreen mode

Save it and open up your browser, you should see (no hero yet and Thanos output to the browser) much like in a normal if else construct the template in the else section gets output to the DOM if our expression evaluates to false. Don't forget to add the colon before the else keyword We can use an else if block rather than using two if statements and let's see how we can do that, edit the App.svelte file and it should be looking like this;

<script>    let hero = 'spiderman'    let villain = 'Thanos'    let showHero = false    let showVillain = true</script><main>    {#if showHero}        <h2>{ hero }</h2>    {:else if showVillain}        <h2>{ villain }</h2>    {:else}        <h2>No Hero or Villain yet</h2>    {/if}</main><style>    h2{        color: grey;    }</style>
Enter fullscreen mode Exit fullscreen mode

We can use the :else if statement to add a another condition to the block and some HTML and if that condition evaluates to true the HTML will be added to the DOM, if it evaluates to false it wont be added to the DOM. let's take a look a repeating templates

Looping with Svelte

Every front-end framework provide a means for you to repeat a template for a given list, and svelte is no different, say we have an array of heroes and we want to repeat a template for each item in hero in the list, let's see how we can do that with svelte, make the following alteration to your App.svelte file;

<script>    let hereos = ['spiderman', 'Deadpool', 'Thor']</script><main>    {#each heroes as hero}        <h2>{ hero }</h2>    {/each</main><style>    h2{        color: grey;    }</style>
Enter fullscreen mode Exit fullscreen mode

Save the file and open up your browser, you should see a list of heroes output to the browser, we use the curly braces and then # sign, followed immediately by the each keyword, next is the list and in this case it is heroes, next we use the as keyword followed by whatever we want to call each item in the list, just like we use a forEach loop, so we use a h2 tag to output the each item in turn and inside the h2 tag, we can tack on an else statement to an each block incase the list we supplied is empty and then svelte will display that message if the list we supplied to it is empty, let's edit our app.svelte file to allow for that;

<script>    let hereos = ['spiderman', 'Deadpool', 'Thor']    let heroes2 = [];</script><main>    {#each heroes2 as hero}        <h2>{ hero }</h2>    {:else}        <p>No hero in the list</p>    {/each</main><style>    h2{        color: grey;    }</style>
Enter fullscreen mode Exit fullscreen mode

save it and open up your browser, you should see no hero in the list inside the browser, because we supplied an empty array. Let's move to using and importing multiple components.

Multiple Components

If we continue writing all our code inside one file, it is going to be a hell to work with and it will become difficult to manage, thus we need to split up our code into multiple components and import them where they are needed, take a list for example, we can have a list item component we can reuse for any list as a separate component and then we import that component into a parent component which will make use of the list item, let's see a typical use case of multiple components, edit your folder structure, inside the src folder create a file and name it Hero.svelte, it should contain the following contents

<script>    let hereos = ['spiderman', 'Deadpool', 'Thor']</script><main>    {#each heroes as hero}        <h2>{ hero }</h2>    {:else}        <p>No hero in the list</p>    {/each</main><style>    h2{        color: grey;    }</style>
Enter fullscreen mode Exit fullscreen mode

save it, open your App.svelte and make the following changes to it;

<script>    import Hero from './Hero.svelte'</script><main>    <Hero /> <!-- Or -->    <Hero></Hero></main><style>    h2{        color: grey;    }</style>
Enter fullscreen mode Exit fullscreen mode

save it and open your browser, you shouldn't see much change from the last time except of course now we get the heroes back in the DOM, however our code has changed, let's look at a few talking points.

  • You will notice that we didn't export anything in our Hero.svelte file yet we are importing it in App.svelte, this is because by default svelte exports every component we create so we don't need to do that our self.
  • Secondly we use a self closing tag to represent the component, we could also use opening and closing tags too and that's fine.

Functions on Events

Certainly our code will need to fire a function when a button is clicked, when a form is submitted, e.t.c. we can do that using on:event={function} where event represents the event we are targeting and function represents a reference to the function we want to run when the event fires, let's see a typical example, Open Hero.svelte and make the following changes to it.

<script>    let hereos = ['spiderman', 'Deadpool', 'Thor']    let logHeroes = () => console.log(heroes)</script><main>    {#each heroes as hero}        <h2>{ hero }</h2>        <button on:click={logHeroes}>log heroes</button>    {:else}        <p>No hero in the list</p>    {/each</main><style>    h2{        color: grey;    }</style>
Enter fullscreen mode Exit fullscreen mode

Open your browser, you should see a button under each hero, open up your browser console and then click on the button, you should see the heroes list output to the console. it is to note that we don't call the function explicitly, rather we pass a reference to the function, this is because if we call the function explicitly, it will fire the code immediately the browser loads up, this is quite similar to a behavior in react. When we pass a function reference to an event, we automatically take in the event object and we can make use of it. Let's see a typical use case;

<script>    let hereos = ['spiderman', 'Deadpool', 'Thor']    let logHeroes = (e) => console.log(e, heroes)</script><main>    {#each heroes as hero}        <h2>{ hero }</h2>          <button on:click={logHeroes}>log heroes</button>    {:else}        <p>No hero in the list</p>    {/each</main><style>    h2{        color: grey;    }</style>
Enter fullscreen mode Exit fullscreen mode

Save it, open your browser and click the button, you should see the event object along with the heroes list output to the console. That's it for this article, stay tuned for more articles on svelte as i will be writing more articles on svelte in the future, hope you enjoyed this one guys.


Original Link: https://dev.to/kalashin1/building-web-apps-with-svelte-4bj7

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To