Svelte is a new JavaScript UI library that’s similar in many ways to modern UI libraries like React. One important difference is that it doesn’t use the concept of a virtual DOM.
In this tutorial, we’ll be introducing Svelte by building a news application inspired by the Daily Planet, a fictional newspaper from the Superman world.
About Svelte
Svelte makes use of a new approach to building users interfaces. Instead of doing the necessary work in the browser, Svelte shifts that work to a compile-time phase that happens on the development machine when you’re building your app.
In a nutshell, this is how Svelte works (as stated in the official blog):
Svelte runs at build time, converting your components into highly efficient imperative code that surgically updates the DOM. As a result, you’re able to write ambitious applications with excellent performance characteristics.
Svelte is faster than the most powerful frameworks (React, Vue and Angular) because it doesn’t use a virtual DOM and surgically updates only the parts that change.
We’ll be learning about the basic concepts like Svelte components and how to fetch and iterate over arrays of data. We’ll also learn how to initialize a Svelte project, run a local development server and build the final bundle.
Prerequisites
You need to have a few prerequisites, so you can follow this tutorial comfortably, such as:
- Familiarity with HTML, CSS, and JavaScript (ES6+),
- Node.js and npm installed on your development machine.
Node.js can be easily installed from the official website or you can also use NVM for easily installing and managing multiple versions of Node in your system.
We’ll be using a JSON API as a source of the news for our app, so you need to get an API key by simply creating an account for free and taking note of your API key.
Getting Started
Now, let’s start building our Daily Planet news application by using the degit tool for generating Svelte projects.
You can either install degit
globally on your system or use the npx tool to execute it from npm. Open a new terminal and run the following command:
npx degit sveltejs/template dailyplanetnews
Next, navigate inside your project’s folder and run the development server using the following commands:
cd dailyplanetnews
npm run dev
Your dev server will be listening from the http://localhost:5000
address. If you do any changes, they’ll be rebuilt and live-reloaded into your running app.
Open the main.js
file of your project, and you should find the following code:
import App from './App.svelte';
const app = new App({
target: document.body,
props: {
name: 'world'
}
});
export default app;
This is where the Svelte app is bootstrapped by creating and exporting an instance of the root component, conventionally called App
. The component takes an object with a target
and props
attributes.
The target
contains the DOM element where the component will be mounted, and props
contains the properties that we want to pass to the App
component. In this case, it’s just a name with the world value.
Open the App.svelte
file, and you should find the following code:
<script>
export let name;
</script>
<style>
h1 {
color: purple;
}
</style>
<h1>Hello {name}!</h1>
This is the root component of our application. All the other components will be children of App
.
Components in Svelte use the .svelte
extension for source files, which contain all the JavaScript, styles and markup for a component.
The export let name;
syntax creates a component prop called name
. We use variable interpolation—{...}
—to display the value passed via the name prop.
You can simply use plain old JavaScript, CSS, and HTML that you are familiar with to create Svelte components. Svelte also adds some template syntax to HTML for variable interpolation and looping through lists of data, etc.
Since this is a small app, we can simply implement the required functionality in the App
component.
In the <script>
tag, import the onMount()
method from “svelte” and define the API_KEY
, articles
, and URL
variables which will hold the news API key, the fetched news articles and the endpoint that provides data:
<script>
export let name;
import { onMount } from "svelte";
const API_KEY = "<YOUR_API_KEY_HERE>";
const URL = `https://newsapi.org/v2/everything?q=comics&sortBy=publishedAt&apiKey=${API_KEY}`;
let articles = [];
</script>
onMount
is a lifecycle method. Here’s what the official tutorial says about 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 runs after the component is first rendered to the DOM.
Next, let’s use the fetch API to fetch data from the news endpoint and store the articles in the articles
variable when the component is mounted in the DOM:
<script>
// [...]
onMount(async function() {
const response = await fetch(URL);
const json = await response.json();
articles = json["articles"];
});
</script>
Since the fetch()
method returns a JavaScript Promise, we can use the async/await syntax to make the code look synchronous and eliminate callbacks.
Next, let’s add the following HTML markup to create the UI of our application and display the news data:
<h1>
<img src="https://dailyplanetdc.files.wordpress.com/2018/12/cropped-daily-planet-logo.jpg?w=656&h=146" />
<p class="about">
The Daily Planet is where heroes are born and the story continues. We are proud to report on the planet, daily.
</p>
</h1>
<div class="container">
{#each articles as article}
<div class="card">
<img src="{article.urlToImage}">
<div class="card-body">
<h3>{article.title}</h3>
<p> {article.description} </p>
<a href="{article.url}">Read story</a>
</div>
</div>
{/each}
</div>
We use the each
block to loop over the news articles and we display the title
, description
, url
and urlToImage
of each article.
The daily planet logo and the headline are borrowed from this nonprofit news organization that’s inspired by DC Comics.
We’ll make use of Kalam, a handwritten font available from Google fonts, so open the public/index.html
file and add the following tag:
<link href="https://fonts.googleapis.com/css?family=Kalam" rel="stylesheet">
Next, go back to the App.svelte
file and add the following styles:
<style>
h1 {
color: purple;
font-family: 'kalam';
}
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(305px, 1fr));
grid-gap: 15px;
}
.container > .card img {
max-width: 100%;
}
</style>
This is a screenshot of our daily news app:
Building for Production
After developing your application, you can create the production bundles by running the build command in your terminal:
npm run build
The command will produce a minified and production-ready bundle that you can host on your preferred hosting server.
Let’s now host the application using ZEIT Now.
ZEIT Now is a cloud platform for websites and serverless functions that you can use to deploy your projects to a .now.sh
or personal domain.
Go back to your terminal and run the following command to install Now CLI:
npm install -g now
Next, navigate to the public
folder and run the now
command:
cd public
now
That’s it! Your application will be deployed to the cloud. In our case, it’s available from public-kyqab3g5j.now.sh.
You can find the source code of this application from this GitHub repository.
Conclusion
In this tutorial, we built a simple news app using Svelte. We also saw what Svelte is and how to create a Svelte project using the degit
tool from npm.
You can refer to the official docs for a detailed tutorial to learn about every Svelte feature.
Frequently Asked Questions (FAQs) about Building a News App with Svelte
What are the key benefits of using Svelte for building a news app?
Svelte is a modern JavaScript compiler that allows you to write easy-to-understand JavaScript code that is then compiled to highly efficient imperative code that directly manipulates the DOM. When building a news app, Svelte offers several benefits. Firstly, it provides a simpler and cleaner code, making it easier for developers to understand and maintain the code. Secondly, Svelte apps are highly performant. Since Svelte runs at build time, it converts the app components into highly efficient imperative code that updates the DOM. This results in faster load times and a smoother user experience. Lastly, Svelte is component-based, just like React and Vue, which makes it easier to build complex user interfaces.
How can I add a new article to the news app built with Svelte?
Adding a new article to your Svelte news app involves creating a new component for the article and then importing it into the relevant parent component. In the new component, you can define the article’s content and any associated metadata like the author and published date. Once the component is created, you can import it into the parent component using the import
statement. Then, you can add it to the parent component’s render method where you want the article to appear.
How can I implement a search functionality in my Svelte news app?
Implementing a search functionality in a Svelte news app involves creating a search component and adding state management to track the search input. You can use Svelte’s built-in reactivity features to update the displayed articles based on the search input. When the search input changes, you can filter the list of articles to only include those that match the search input.
How can I categorize news articles in my Svelte app?
Categorizing news articles in a Svelte app can be achieved by adding a category property to each article. This property can then be used to filter the articles based on the selected category. You can create a categories component that displays a list of categories. When a category is selected, you can update the displayed articles to only include those in the selected category.
How can I add user authentication to my Svelte news app?
Adding user authentication to a Svelte news app can be done using various methods, such as using the Firebase Authentication service or a backend server with JWT (JSON Web Tokens). You would need to create an authentication component where users can enter their login credentials. Upon form submission, these credentials are sent to the authentication service or backend server for verification. If the credentials are valid, the user is authenticated and granted access to the app.
How can I make my Svelte news app responsive?
Making a Svelte news app responsive involves using CSS media queries to adjust the app’s layout based on the screen size. Svelte allows you to write CSS code in the same file as your JavaScript and HTML code, making it easier to style your components. You can define different styles for different screen sizes to ensure your app looks good on all devices.
How can I add push notifications to my Svelte news app?
Adding push notifications to a Svelte news app can be done using a service like Firebase Cloud Messaging. You would need to register your app with the service and then add the necessary code to your app to handle receiving push notifications. This typically involves adding a service worker to your app that listens for push events and displays the notification when one is received.
How can I add a comment section to my Svelte news app?
Adding a comment section to a Svelte news app involves creating a comments component and adding state management to track the comments. You can use Svelte’s built-in reactivity features to update the comments based on user input. When a user submits a comment, you can add it to the list of comments and update the displayed comments.
How can I optimize the performance of my Svelte news app?
Optimizing the performance of a Svelte news app can involve several strategies. Firstly, you can use Svelte’s built-in tools for code splitting and lazy loading to only load the code that’s needed for the current view. Secondly, you can optimize your images and other static assets to reduce their file size. Lastly, you can use a service worker to cache your app’s assets and serve them from the cache, reducing the load time.
How can I deploy my Svelte news app?
Deploying a Svelte news app can be done using various methods, such as using a static site hosting service like Netlify or Vercel, or a cloud platform like Google Cloud or AWS. You would need to build your app for production using the npm run build
command, which creates a public
folder with your compiled app. This folder can then be uploaded to your hosting service or cloud platform.
Ahmed is a technical author and web developer living in Morocco with a Master's degree in software development. He authors technical content about JavaScript, Angular and Ionic. He is also a fan of entrepreneurship, poetry, and teaching. You can contact me on my personal website and read my other articles on Techiediaries.