Pantas dan Selaras dengan Svelte

PHPz
Lepaskan: 2024-08-22 22:33:10
asal
384 orang telah melayarinya

Are you ready to build a reactive real-time web application?

tl;dr Don’t have time to read and work through this entire tutorial? You’re in luck! You can find a fully working example onGitHub. Feel free to go there, clone the repository and start exploring.


In this tutorial, we’ll explore the combination of Svelte and Couchbase Capella to create a dynamic and interactive chat application. Svelte, with an impressive 72.8% admiration rate according to the 2024 Stack Overflow Developer Survey, is celebrated for several reasons. It efficiently takes much of the work out of the browser by compiling your components into highly efficient, imperative code that directly manipulates the DOM, eliminating the need for a virtual DOM and leading to faster updates and smaller bundle sizes.

Svelte’s built-in reactivity automatically tracks state changes, ensuring fast and efficient updates without the need for complex state management libraries. This reactivity simplifies the development process and enhances performance. Additionally, Svelte’s component-based architecture makes it easier to build and maintain complex user interfaces, offering a more straightforward and enjoyable development experience. And, when your application needs responsive, adaptive data Couchbase Capella offers a straightforward solution to implement.

Couchbase Capella is not just a NoSQL cloud database platform; it’s an all-in-one data platform offering full-text search, vector search, data caching, analytics, and more. This comprehensive functionality allows you to build robust applications with diverse data requirements. Together, Svelte and Couchbase Capella make possible real-time applications that are blazingly fast and performant.

Okay, enough talk. Let’s get started!

Setting up the Dev Environment

Creating a New SvelteKit Project

Before diving into the setup, let’s clarify the difference between Svelte and SvelteKit. Svelte is a front-end framework that compiles your code into highly efficient, imperative code that directly manipulates the DOM. This results in faster updates and smaller bundle sizes. On the other hand, SvelteKit is a framework built on top of Svelte, designed for building full-stack web applications. SvelteKit provides additional features such as routing, server-side rendering, and static site generation, making it a powerful tool for developing modern web applications.

In your project, SvelteKit will handle the application structure, routing, and server-side rendering, while Svelte will manage the efficient rendering of UI components.

To start a new project you can initialize it on the command line:

> npm create svelte@latest svelte-couchbase-real-time-chat > cd svelte-couchbase-real-time-chat
Salin selepas log masuk

You will be prompted with several choices by the CLI tool. Answer with the following responses:

  • -Skeleton Project: Selectyesto start with a basic project structure.
    • Typescript: Selectnofor now to keep things simple.
    • ESLint: Selectyesto include linting, which helps in maintaining code quality.
    • Prettier: Selectyesfor code formatting.
    • Playwright: Selectnounless you plan to write end-to-end tests from the beginning.

Then, install the dependencies by runningnpm installfrom the command line. After running these commands, you’ll have a new SvelteKit project set up and ready to go!

Installing Dependencies

Next, we’ll install additional dependencies required for our project, including Tailwind CSS for styling, the Couchbase SDK for database interactions, and WebSocket support for real-time communication.

> npm install -D tailwindcss postcss autoprefixer couchbase ws dotenv > npx tailwindcss init -p
Salin selepas log masuk

What are each of these dependencies doing in your application?

  • TailwindCSS is a utility-first CSS framework that makes it more straightforward to style your application with predefined classes.
  • The Couchbase Node.js SDK introduces functionality to interact with your data on Couchbase Capella using methods that abstract away a lot of the work.
  • wsis a small Websocket library for Node.js. You will be enabling the real-time chat functionality in the application with Websockets.
  • Lastly,dotenvloads environment variables from a.envfile intoprocess.envmaking it easier to manage configuration.

Configuring TailwindCSS

As mentioned above, TailwindCSS introduces classes that you can use to define the styling for your application. This is helpful if you are not a frontend expert, or even if you are, if you wish to shortcut the process of building elegantly designed applications. To use TailwindCSS in your Svelte project, follow these steps:

Configuretailwind.config.js

Update thetailwind.config.cjsfile to specify the content sources. This ensures that Tailwind CSS can remove unused styles from your production build, making it more efficient.

/** @type {import('tailwindcss').Config} */ module.exports = { content: ['./src/**/*.{html,js,svelte,ts}'], theme: { extend: {}, }, plugins: [], }
Salin selepas log masuk

Add Tailwind CSS directives

Create or update thesrc/app.cssfile to include Tailwind CSS directives. These directives load Tailwind’s base, components, and utility styles.

@tailwind base; @tailwind components; @tailwind utilities;
Salin selepas log masuk

Include the CSS in your Svelte project

Open or create thesrc/routes/+layout.sveltefile and import the CSS file. This ensures that Tailwind’s styles are available throughout your application.

 
Salin selepas log masuk

Now that you’ve completed these steps, TailwindCSS has been successfully initialized in your application! You’re ready to move on to setting up Couchbase Capella and building the backend for your chat application.

Setting Up Couchbase Capella

Creating a Cluster

It is free to sign up and try Couchbase Capella, and if you have not done so yet, you can do so by navigating to cloud.couchbase.com and creating an account using your GitHub or Google credentials, or by making a new account with an email address and password combination.

Once you have done so, from within your Capella dashboard, you will create your first cluster. For the purposes of this walkthrough, let’s name itSvelteChatApp.

The summary of your new cluster will be presented on the left-hand side of the dashboard. Capella is multi-cloud and can work with AWS, Google Cloud or Azure. For this example, you will deploy to AWS.

After you have created your cluster, you need to create abucket. Abucketin Couchbase is the container where the data is stored. Each item of data, known as a document, is kept in JSON making its syntax familiar to most developers. You can name your bucket whatever you want. However, for the purposes of this walkthrough, let’s name this bucketsvelte_chat_app_messages.

Now that you have created both your database and your bucket, you are ready to create your database access credentials and to fetch your connection URL that you will be using in your Lambda function.

Obtaining Connection Details

The connection details are essential as you will be using them in your application to establish a connection to your Couchbase data and to interact with the data. Navigate to theConnectsection in the Capella dashboard and take note of theConnection String.

Quick and In Sync with Svelte

Then, click on theDatabase Accesslink under section two. In that section, you will create credentials – a username and password – that your application will use to authenticate with the database. You can scope the credentials to the specific bucket you created or give it permission for all buckets and databases in your account. You need to make sure it has both read and write access, regardless.

Once you have finished, the last step in this part of the process is to add your new connection string and connection credentials to your application as environment variables.

Setting Up Environment Variables

In a production environment, you will store your credentials and other confidential information for your application in a secure format. Different cloud providers have different paths to store sensitive information, and you should follow the procedure defined by the cloud provider you are using, whether it is AWS, Google Cloud, Azure, Netlify, Vercel or any other. For our purposes, you are adding your credentials to a.envfile in the root folder of your application. Thedotenvpackage reads those credentials from there and loads them into your application.

# .env COUCHBASE_BUCKET=your_bucket_name COUCHBASE_CONNECTION_STRING=your_connection_string COUCHBASE_USER=your_username COUCHBASE_PASSWORD=your_password
Salin selepas log masuk

That’s it! Your Couchbase cluster is all set up and ready to be used. At this point, you are ready to build the application. Let’s start with the backend server with Nodejs and then move on to the frontend with Svelte.

Building the Backend with Node.js

With our development environment set up, it’s time to build the backend for our real-time chat application. We’ll use Node.js to create the server, connect to Couchbase Capella for data storage, and set up a WebSocket server for real-time communication.

Creatingserver.cjs

First, we’ll create a file named server.cjs which will serve as the entry point for our backend.

    1. Createserver.cjs: In the root directory of your project, create a new file namedserver.cjs.
    1. Setup Express and Dependencies: We’ll use Express for our server framework, the Couchbase SDK for database operations, WebSocket for real-time communication, anddotenvfor environment variables management. Add the following code toserver.cjs:
const express = require('express'); const couchbase = require('couchbase'); const { createServer } = require('http'); const { WebSocketServer } = require('ws'); const dotenv = require('dotenv'); dotenv.config(); const app = express(); const server = createServer(app); const wss = new WebSocketServer({ server });
Salin selepas log masuk

Connecting to Couchbase

Next, we’ll set up the connection to Couchbase Capella. Ensure your .env file contains the correct connection details. Add the following code toserver.cjsto connect to Couchbase:

let cluster, bucket, collection; async function connectToCouchbase() { try { console.log('Connecting to Couchbase...'); const clusterConnStr = process.env.COUCHBASE_CONNECTION_STRING; const username = process.env.COUCHBASE_USER; const password = process.env.COUCHBASE_PASSWORD; const bucketName = process.env.COUCHBASE_BUCKET; cluster = await couchbase.connect(clusterConnStr, { username: username, password: password, configProfile: 'wanDevelopment', }); bucket = cluster.bucket(bucketName); collection = bucket.defaultCollection(); console.log('Connected to Couchbase successfully.'); } catch (error) { console.error('Error connecting to Couchbase:', error); process.exit(1); } } connectToCouchbase();
Salin selepas log masuk

This function handles the connection to Couchbase, ensuring that all necessary parameters are properly configured. All that is left for our backend is to create the websocket server to handle the sending and receiving of new chat messages.

Setting up the Websocket Server

The Websocket server functionality is also added to theserver.cjsfile. The server will broadcast all new messages for the frontend of the application to receive, and send all newly created messages to Couchbase for saving in the bucket you created.

wss.on('connection', (ws) => { console.log('New WebSocket connection established.'); ws.on('message', async (message) => { try { const messageString = message.toString(); console.log('Received message:', messageString); // Save message to Couchbase const id = `message::${Date.now()}`; await collection.upsert(id, { text: messageString }); console.log('Message saved to Couchbase:', id); // Broadcast message wss.clients.forEach((client) => { if (client.readyState === WebSocket.OPEN) { client.send(messageString); console.log('Broadcasted message to client:', messageString); } }); } catch (error) { console.error('Error handling message:', error); } }); }); server.listen(3000, () => { console.log('Server started on http://localhost:3000'); });
Salin selepas log masuk

Note that before sending the message to Couchbase, you first convert the message into aStringas it is received as binary data buffers by default. The conversion toStringformat is achieved by calling thetoString()function on the message. The newly definedmessageStringvariable now contains the data in readable format for both sending to Couchbase and rendering in the application.

That is the entire backend of your new real-time chat application. However, as good as any backend for a web application is, it needs a frontend to render it for the user. Svelte offers us the performance and reactivity to do so with speed and with an excellent developer experience.

Creating the Frontend with Svelte

With your backend set up, it’s time to build the frontend of our real-time chat application using Svelte. You’ll leverage Svelte’s strengths to create a responsive and dynamic chat interface.

Building the Chat Interface

  1. Create the Svelte Component In your SvelteKit project, create a new file named+page.sveltein thesrc/routesdirectory. This file will serve as the main component for our chat interface.
touch src/routes/+page.svelte
Salin selepas log masuk
  1. Set Up the Basic Structure Open+page.svelteand set up the basic HTML structure with TailwindCSS classes for styling:
 

Chat Application

{#each messages as message}
{message}
{/each}
Salin selepas log masuk

Thesection of the above code example initializes Websocket and handles the messages, both sending and receiving. TheonMountfunction ensures that the Websocket connection is established when the component is initialized. Svelte’s reactivity automatically updates the DOM whenever themessagesarray changes, ensuring new messages are displayed in real-time. With that your frontend is now complete.

You did it! You have built an entire chat application enabling real-time communication utilizing the performance, flexibility and adaptability of both Svelte and Couchbase to deliver an optimal experience for your users. Yes, this is a fairly simple implementation, however, it provides the skeleton for you to build even more expansive and complex real-time applications. The potential is only limited by your imagination.

Ingin mencubanya? Mari mulakan aplikasi anda dan mula bersembang.

Menjalankan aplikasi

Untuk menjalankan aplikasi anda, anda akan memulakan pelayan Node.js hujung belakang dan bahagian hadapan SvelteKit. Mula-mula, mari mulakan bahagian belakang dari terminal anda:

Kemudian, mulakan bahagian hadapan dalam tetingkap terminal baharu:

Sekarang, navigasi dalam penyemak imbas anda kehttp://localhost:5173dan mula bersembang!

Quick and In Sync with Svelte

Anda boleh membuka berbilang tab penyemak imbas untuk mensimulasikan berbilang pengguna atau menggunakan perkhidmatan seperti ngrok untuk berkongsi aplikasi dengan rakan anda dan bersembang dalam masa nyata dengan mereka.

Membungkus

Dalam tutorial ini, anda telah mempelajari seberapa pantas anda boleh mencipta aplikasi responsif sepenuhnya yang berfungsi dengan data masa nyata. Svelte mengemas kini DOM dengan mudah, manakala Couchbase membolehkan anda mula mencipta dan menyimpan mesej dalam beberapa saat sahaja.

Terdapat banyak sebab mengapa Svelte berkembang pesat dalam kekaguman dan populariti dalam ruang rangka kerja web yang sangat kompetitif. Couchbase sebagai bahagian belakang data yang digandingkan dengan Svelte meningkatkan potensi untuk perkara yang boleh anda bina dan capai dengan lebih banyak lagi. Tidak perlu mentakrifkan skema yang rumit, tidak perlu menambah lebih banyak kebergantungan di kemudian hari jika anda ingin melaksanakan caching data atau keupayaan carian, semuanya disertakan dengan Couchbase dan datang terus dari kotak.

Satu-satunya soalan yang tinggal ialah: Apakah yang akan anda bina seterusnya?

Mulakan secara percuma menggunakan Couchbase Capella.

Atas ialah kandungan terperinci Pantas dan Selaras dengan Svelte. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!