search
HomeWeb Front-endJS TutorialSvelte App Project: Build the Daily Planet's News App UI

Svelte App Project: Build the Daily Planet's News App UI

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.

Key Takeaways

  • Svelte is a new JavaScript UI library that doesn’t use a virtual DOM, making it faster than most powerful frameworks like React, Vue, and Angular. It shifts the necessary work to a compile-time phase on the development machine when building the app.
  • The tutorial provides a step-by-step guide on building a news application inspired by the Daily Planet, a fictional newspaper from the Superman world. This includes initializing a Svelte project, running a local development server, and building the final bundle.
  • The tutorial also covers the use of the degit tool for generating Svelte projects, fetching data from a news endpoint, and creating the UI for the application.
  • After developing the application, one can create the production bundles by running the build command in the terminal and host the application using ZEIT Now, a cloud platform for websites and serverless functions.

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:

<span>cd dailyplanetnews
</span><span>npm run dev
</span>

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:

<span>import <span>App</span> from './App.svelte';
</span>
<span>const app = new App({
</span>    <span>target: document.body,
</span>    <span>props: {
</span>        <span>name: 'world'
</span>    <span>}
</span><span>});
</span>
<span>export default app;
</span>

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:

<span><span><span><script>></script></span><span>
</span></span><span><span>    <span>export let name;
</span></span></span><span><span></span><span><span></span>></span>
</span>
<span><span><span><style>></style></span><span>
</span></span><span><span>    <span>h1 {
</span></span></span><span><span>        <span>color: purple;
</span></span></span><span><span>    <span>}
</span></span></span><span><span></span><span><span></span>></span>
</span>
<span><span><span><h1 id="gt">></h1></span>Hello {name}!<span><span></span>></span>
</span></span></span></span>

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>

<span><script>
</script></span>    <span>export let name;
</span>
    <span>import <span>{ onMount }</span> from "svelte";
</span>
    <span>const API_KEY = "<your_api_key_here>";
</your_api_key_here></span>    <span>const URL = <span>`https://newsapi.org/v2/everything?q=comics&sortBy=publishedAt&apiKey=<span>${API_KEY}</span>`</span>;
</span>    <span>let articles = [];
</span>
<span>
</span>

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:

npx degit sveltejs/template dailyplanetnews

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:

<span>cd dailyplanetnews
</span><span>npm run dev
</span>

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:

<span>import <span>App</span> from './App.svelte';
</span>
<span>const app = new App({
</span>    <span>target: document.body,
</span>    <span>props: {
</span>        <span>name: 'world'
</span>    <span>}
</span><span>});
</span>
<span>export default app;
</span>

Next, go back to the App.svelte file and add the following styles:

<span><span><span><script>></script></span><span>
</span></span><span><span>    <span>export let name;
</span></span></span><span><span></span><span><span></span>></span>
</span>
<span><span><span><style>></style></span><span>
</span></span><span><span>    <span>h1 {
</span></span></span><span><span>        <span>color: purple;
</span></span></span><span><span>    <span>}
</span></span></span><span><span></span><span><span></span>></span>
</span>
<span><span><span><h1 id="gt">></h1></span>Hello {name}!<span><span></span>></span>
</span></span></span></span>

This is a screenshot of our daily news app:

Svelte App Project: Build the Daily Planet's News App UI

Building for Production

After developing your application, you can create the production bundles by running the build command in your terminal:

<span><script>
</script></span>    <span>export let name;
</span>
    <span>import <span>{ onMount }</span> from "svelte";
</span>
    <span>const API_KEY = "<your_api_key_here>";
</your_api_key_here></span>    <span>const URL = <span>`https://newsapi.org/v2/everything?q=comics&sortBy=publishedAt&apiKey=<span>${API_KEY}</span>`</span>;
</span>    <span>let articles = [];
</span>
<span>
</span>

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:

<span><script>
</script></span>    <span>// [...]
</span>
    <span>onMount(async function() {
</span>        <span>const response = await fetch(URL);
</span>        <span>const json = await response.json();
</span>        articles <span>= json["articles"];
</span>    <span>});
</span><span>    
</span>

Next, navigate to the public folder and run the now command:

<span><span><span><h1 id="gt">></h1></span>
</span>    <span><span><span><img  alt="Svelte App Project: Build the Daily Planet&#x27;s News App UI" > src<span>="https://dailyplanetdc.files.wordpress.com/2018/12/cropped-daily-planet-logo.jpg?w=656&h=146"</span> /></span>
</span>    <span><span><span><p> class<span>="about"</span>></p></span>
</span>            The Daily Planet is where heroes are born and the story continues. We are proud to report on the planet, daily.
    <span><span><span></span>></span>
</span><span><span><span></span>></span>
</span>
<span><span><span><div> class<span>="container"</span>>

        {#each articles as article}
            <span><span><span><div> class<span>="card"</span>>
                <span><span><span><img  alt="Svelte App Project: Build the Daily Planet&#x27;s News App UI" > src<span>="{article.urlToImage}"</span>></span>
</span>                <span><span><span><div> class<span>="card-body"</span>>
                    <span><span><span><h3 id="gt">></h3></span>{article.title}<span><span></span>></span>
</span>                    <span><span><span><p>></p></span> {article.description} <span><span></span>></span>
</span>                    <span><span><span><a> href<span>="{article.url}"</span>></a></span>Read story<span><span></span>></span>
</span>                <span><span><span></span></span></span></span></span></span>
</div></span>></span>
</span>            <span><span><span></span></span></span></span>
</div></span>></span>
</span>        {/each}

<span><span><span></span></span></span>
</div></span>></span>
</span></span></span></span>

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.

The above is the detailed content of Svelte App Project: Build the Daily Planet's News App UI. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.