Svelte Js Tutorial: Building a simple web app (a click-to-tweet generator)

And deploy it using Netlify

XQ
The Research Nest
12 min readJan 14, 2021

--

With a lot of developers taking notice of the new Svelte framework, I thought I will explore a bit of it. As with most of my learning experiments, I got started with actually building something tangible and documenting the process. This tutorial will be super beginner-friendly and I hope even those who haven’t written a single line of code before can follow easily. Also, the focus won’t be just on “programming”, but also on “thinking”. The insights mentioned here can be applied to any kind of project you want to build.

What is Svelte? First impressions

In simple terms, it is something that helps you build websites, web apps, and stuff like that. After examining the basic use cases and functionalities, here’s what I felt about Svelte (rhyming!?)-

  • It is super easy to learn. I found it a lot simpler than React/Redux (another framework for UI development). I think even the non-tech people can learn it pretty quickly. If you are just beginning web development, I would recommend you to try it out.
  • It is structured in a compact way. I personally found the hierarchy of the code better than React. It is kind of debatable though.
  • It feels like a good choice to quickly build some simple single page websites. While I haven’t explored enough to comment on complex web applications and performance metrics, so far, React feels much better for them.

If you want to know more, here is a good intro video-

For those who are curious about the origins of Svelte and why it was created in the first place, I would highly recommend them to watch this video as well-

Getting started with Svelte- Project-based learning

Recently, I have launched a newsletter on LinkedIn called Self-learning Tech. I wanted to give my readers a specific functionality, which LinkedIn natively doesn’t provide- To tweet specific sentences from the article.

This is a very straight forward process where you basically have to create a URL that will take you to your Twitter account and autofill the tweet content so that you can tweet instantly at the click of a button. So, the idea was to hyperlink the individual sentences (i.e the punchlines :D) that people would like to tweet with these URLs.

For example, a simple tweet URL would look something like this-

If you visit the URL, you will be taken to twitter.com and you will see the following tweet auto-filled.

Depending on the complexity of the tweet, the URL also gets complex. I didn’t want to create it manually or use some existing 3rd party tools for it. That’s when I thought to build something of my own (Read till the end to know why).

It is essentially just a URL generator and I thought the idea sounded perfect to build in Svelte to learn and explore the basics.

Takeaways

  • I would always recommend you to think of a unique real-world application that you might personally use for project ideas.
  • Learning by doing such projects adds a new layer of context to the learning process. It is no longer just a project but a product with 1 user i.e you. It is plausible that there will be other users who would want to use it as well.

Designing the project

Before you jump into the programming part, it is important to get the design aspects and product logic first. The URL we want to create requires 4 parameters:

  • The tweet content
  • URL to some article, link, etc. that you want to share in the tweet
  • Hashtags
  • Twitter username of someone you want to tag in the tweet.

We have to get these inputs from the user. The straightforward way is to create a form and let the user enter the details. Once we get the input, we can have a function to generate the required URL string. It can then be presented to the user to copy it and use it wherever they want.

Simple, right?

Takeaways

  • By building these, we will essentially learn to build any kind of web form- say, a contact me form, or a subscription form, or feedback form, etc.
  • We will also learn how to write and use functions in Svelte

Thinking about styling

Style is as important as the logic itself. As a developer, we may tend to give less importance to it but I would encourage otherwise. No one would prefer to use an app that doesn’t look good or when the UX feels broken and confusing. With the basic idea set, I visualized a bit on how I want the app to look like.

This is how the web app would have looked like without any styling

Style choices

  • The first thing was the color scheme. I personally wanted it to be in dark mode. Since it is about Twitter, I picked the colours based on Twitter’s dark mode.
  • Then I finalised on the overall look- the spacing, the shape and colours of the buttons, background, help text, and form fields.

Here’s the final design.

Much better? (I hope)

Takeaways

  • I think it is very important that you finalize your basic design before you start to code.
  • Once you know how you want it to look like, things get a lot clear during development.
  • You can use free tools like Figma to make these mock designs if required.

For this project, I simply visualized myself as it was a pretty simple UI.

Programming your web app in Svelte

At this stage, you know exactly what you want to build. So, how to actually build it? Let me assume that you have just started with web development. Here’s how you can approach.

  • The best place to start with any kind of programming framework is from the official website documentation and some online IDE.
  • Svelte has beautiful documentation on how to get started and an online compiler with interactive examples and tutorials.
  • As a first step, go through all of them. Try to change the code, variables and parameters in the editor and check how the output is affected. Piece together the logical flow between the code and output.

After exploring for some time, here are a few things I observed.

  1. Svelte files have .svelte extension. That’s how we save them (obviously).
  2. Every svelte file has three distinct parts- Script, Style and the HTML.

This much context is enough for us to get started!

Note- At the time of writing of this article, svelte version 3.31.2 was used.

Divide and conquer

One of the best ways to proceed further is in a decentralised manner. See if you can break your application into smaller independent components and implement them separately. That way you will have more flexibility in reusing what you built elsewhere. Code will also be less cluttered in the main app. Notice the independent components in our app.

  1. The main app consists of a title, a web form to fill in the details, the help hover text and some buttons, and the footer.
  2. Identify the reusable components- the buttons, the input field in the web form, and the help hover text.
  3. Identify the utility functions you need- Generate, Copy string, and clear all.

Now let’s build each of these components and functions. All the details related to creating your first project are here-

I used the first method and downloaded the project folder into my desktop from Svelte REPL and renamed the folder as “click-to-tweet-app”. (For the first time programmers, I recommend using VS Code for coding)

This is how the folder structure looks like for me.

Everything is already there and we only need to work with the src (source) folder.

The steps to follow

  • Create a sub-folder called shared under src where all the reusable components will be put.
  • Add a strings.js file under src to keep all the constant strings used in the application at one place.
  • Create a utils.js file under src to store all common utility functions. In my case, I had two of them. One helps in copying the string to the clipboard and the other one creates the required URL and then encodes it. Most of the code you see here is based on standard syntax and templates you can easily find online, which I modified a little as per my requirements.
utils.js
  • Next, let’s create the shared components CustomButton, CustomInput, and Helpunder the shared folder. If you have gone through the Svelte documentation before reading further, you will notice that the custom components are created based on the official tutorials and examples provided. I have tweaked the styling and properties as per my need. Adding the Gists below as for some reason carbon was not showing preview with Svelte code. Note that the script part contains the variables related to the component, style part implements the design, look, and feel as per what we want, and the HTML code at the end calls the default components.

I can now simply import and reuse these components wherever I want.

Code Assemble!

It’s time to build our actual application. Here’s the source code for TweetForm.svelte which is another component I made using the shared components. It will render the main input form along with the buttons as you have seen in the UI design.

If you are a first-time programmer going through all these code samples, make a note of these observations-

  • Notice how we are importing the shared components and common functions at the top.
  • Also, notice how we are declaring different variables that we need.
  • I will come back to the style part later. Carefully go through the HTML in the above code snippet. Check how the shared components are being used. I would recommend you to go back to those shared component files and observe the code for more clarity.

Assembling everything into app.svelte

  • App.svelte is the main file of the application.
  • Observe the compactness of the file. We are just importing the TweetForm which takes care of everything internally.
  • We have given styling to the title, sub-title, and the main container. It is pretty straight forward as to what style they are applying to our components.
  • In the HTML part, we have <div> element with class="main". That’s the attribute used to apply the corresponding styling to that element. You can comprehend with similar logic whenever you see any HTML tags.

Running the web app locally, debugging and styling

From official documentation.

You can go to your project folder in the command prompt if you are on Windows using the cd command, and run the commands as mentioned. Once your development server starts, you will be able to access the app in your localhost.

Note that every time you make a change to your code while running it, the local host is refreshed, reflecting the latest changes. This is super useful for easy debugging and styling.

Throughout the code samples shared, you would have seen a lot of parameters set for styling. You can now check the effects in real-time by making changes in those parameters. That way you will get a good clarity on how its working and the exact values needed to render it the way you want.

Deploying your website using Netlify

You can actually use any kind of cloud server. Here, I thought I will explore Netlify which is free and super easy to use. Here are some steps you can follow.

  • Push your repository to Github. (If you don’t have an account, you can create one!)
  • These days, you do not even need to know the git commands to work with git. You can directly use the GitHub Desktop app.

The UI and options you have here are self-explanatory. For a basic understanding, you can refer to this article-

  • Once you have your completed project on Github, you can create an account on Netlify with your GitHub account.
  • You can then visit:
  • Select the “New site from Git” under the “Sites” tab.
  • You will get a screen as below and you can follow the steps as instructed.
  • After choosing the repository to deploy, in build options part, fill in as follows-
  • Click on “Deploy Site”, and viola! The site should be live in a few seconds.
  • The best part here is continuous integration. Whenever you push new changes to your source code in GitHub, it will automatically trigger a new build and update your site!

Here’s the live version of Click-to-tweet-app we have built for this tutorial (best viewed in desktop/laptop)-

What Next?

  • Buttons and input form fields are some of the most basic elements of websites. They are present everywhere.
  • Using a similar approach as to how TweetForm was programmed, you can build other kinds of forms like Contact form, subscription form, feedback form, etc. as previously mentioned.
  • Notice how the shared components can be reused elsewhere. In fact, the TweetForm can be modified into a shared component in such a way that all other forms can be directly built by simply importing it.

At the beginning of the tutorial, I mentioned that I wanted to make my own version of “click-to-tweet” instead of using something that's already available out there. Here’s how such an approach helps-

  • More flexibility in customization and adding personalized and premium features.
  • For example, we could add functions to automatically generate trending hashtags based on what content we are sharing.
  • Likewise, the tweet content can also be auto-generated if required, based on the URL shared.
  • There are so many possibilities and this creative freedom comes from having your own app.
  • There is also more flexibility in the integration of this tool elsewhere if required.

A note to the first time programmers

You might have got a lot of questions while going through this article.

What is cd or npm? How to use git? How do I know the code to create those functions? What’s that bind attribute? The list might be huge and that's a healthy sign.

Just simply google search any kind of “What” and “How” doubt you get. I call it Question-based learning. The concepts covered in this tutorial are basic and can be grasped with minimum support. A simple Google search is more than enough.

Beyond that, don’t forget to be curious. Break the code, make changes and see what’s happening to the output. Ask yourself, the “Why” and “Why not” questions as well. This is Observation-based learning.

The more mistakes you make, the less you repeat in future. In fact, it is a good thing if the code doesn’t work in the first run. Try to figure it out yourself, and fix it. That’s exactly what I did while preparing this tutorial.

Also, notice the real-world applicability of what we are building. I am personally a user of this click-to-tweet tool already and have used it while writing my second newsletter.

Complexity always comes after utility. A good project is something people can use, and one way to validate your idea is to check if you personally would be a user of it.

Here’s the GitHub repository for this project:

Endnote- I am pretty sure this project can be improvised in multiple ways. Feel free to add in your suggestions in the responses or you can directly ping me on LinkedIn.

#StayTuned for more tutorials on Svelte!

--

--

XQ
The Research Nest

Exploring tech, life, and careers through content.