您准备好构建反应式实时 Web 应用程序了吗?
tl;dr 没有时间阅读和完成整个教程?你很幸运!您可以在 GitHub 上找到完整的示例。请随意前往那里,克隆存储库并开始探索。
在本教程中,我们将探索 Svelte 和 Couchbase Capella 的组合来创建动态交互式聊天应用程序。根据 2024 年 Stack Overflow 开发者调查,Svelte 的赞赏率达到了令人印象深刻的 72.8%,它之所以受到赞誉有几个原因。它通过将组件编译为直接操作 DOM 的高效命令式代码,消除了对虚拟 DOM 的需求,从而实现更快的更新和更小的包大小,从而有效地从浏览器中完成大部分工作。
Svelte 的内置反应性会自动跟踪状态变化,确保快速高效的更新,而无需复杂的状态管理库。这种反应性简化了开发过程并提高了性能。此外,Svelte 基于组件的架构可以更轻松地构建和维护复杂的用户界面,从而提供更简单、更愉快的开发体验。而且,当您的应用程序需要响应式、自适应数据时,Couchbase Capella 提供了一个简单的实施解决方案。
Couchbase Capella 不仅仅是一个 NoSQL 云数据库平台;它是一个一体化数据平台,提供全文搜索、矢量搜索、数据缓存、分析等。这种全面的功能使您能够构建具有不同数据需求的强大应用程序。 Svelte 和 Couchbase Capella 共同打造了速度极快、性能卓越的实时应用程序。
好了,说得够多了。让我们开始吧!
在深入了解设置之前,让我们先澄清一下 Svelte 和 SvelteKit 之间的区别。 Svelte 是一个前端框架,可将您的代码编译为直接操作 DOM 的高效命令式代码。这会带来更快的更新和更小的捆绑包大小。另一方面,SvelteKit 是一个构建在 Svelte 之上的框架,旨在构建全栈 Web 应用程序。 SvelteKit 提供了路由、服务器端渲染和静态站点生成等附加功能,使其成为开发现代 Web 应用程序的强大工具。
在您的项目中,SvelteKit 将处理应用程序结构、路由和服务器端渲染,而 Svelte 将管理 UI 组件的高效渲染。
要启动新项目,您可以在命令行上初始化它:
> npm create svelte@latest svelte-couchbase-real-time-chat > cd svelte-couchbase-real-time-chat
CLI 工具将提示您几个选择。请回答以下问题:
然后,通过从命令行运行 npm install 来安装依赖项。运行这些命令后,您将设置一个新的 SvelteKit 项目并准备就绪!
接下来,我们将安装项目所需的其他依赖项,包括用于样式设置的 Tailwind CSS、用于数据库交互的 Couchbase SDK 以及用于实时通信的 WebSocket 支持。
> npm install -D tailwindcss postcss autoprefixer couchbase ws dotenv > npx tailwindcss init -p
这些依赖项在您的应用程序中执行什么操作?
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:
Update the tailwind.config.cjs file 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: [], }
Create or update the src/app.css file to include Tailwind CSS directives. These directives load Tailwind’s base, components, and utility styles.
@tailwind base; @tailwind components; @tailwind utilities;
Open or create the src/routes/+layout.svelte file and import the CSS file. This ensures that Tailwind’s styles are available throughout your application.
<script> import "../app.css"; </script> <slot />
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.
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 it SvelteChatApp.
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 a bucket. A bucket in 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 bucket svelte_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.
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 the Connect section in the Capella dashboard and take note of the Connection String.
Then, click on the Database Access link 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.
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 .env file in the root folder of your application. The dotenv package 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
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.
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.
First, we’ll create a file named server.cjs which will serve as the entry point for our backend.
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 });
Next, we’ll set up the connection to Couchbase Capella. Ensure your .env file contains the correct connection details. Add the following code to server.cjs to 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();
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.
The Websocket server functionality is also added to the server.cjs file. 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'); });
Note that before sending the message to Couchbase, you first convert the message into a String as it is received as binary data buffers by default. The conversion to String format is achieved by calling the toString() function on the message. The newly defined messageString variable 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.
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.
touch src/routes/+page.svelte
<script> import { onMount } from 'svelte'; let messages = []; let newMessage = ''; let ws; onMount(() => { ws = new WebSocket('ws://localhost:3000'); ws.onmessage = (event) => { messages = [...messages, event.data]; }; ws.onopen = () => { console.log('WebSocket connection opened'); }; ws.onclose = () => { console.log('WebSocket connection closed'); }; }); function sendMessage() { ws.send(newMessage); newMessage = ''; } </script> <div class="container mx-auto p-4"> <h1 class="text-2xl mb-4">Chat Application</h1> <div class="border p-4 mb-4 h-64 overflow-y-scroll"> {#each messages as message} <div>{message}</div> {/each} </div> <input type="text" bind:value={newMessage} class="border p-2 w-full mb-2" placeholder="Type a message" /> <button on:click={sendMessage} class="bg-blue-500 text-white p-2 w-full">Send</button> </div>
The section of the above code example initializes Websocket and handles the messages, both sending and receiving. The onMount function ensures that the Websocket connection is established when the component is initialized. Svelte’s reactivity automatically updates the DOM whenever the messages array 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.
想尝试一下吗?让我们启动您的应用程序并开始聊天。
要运行您的应用程序,您将初始化后端 Node.js 服务器和 SvelteKit 前端。首先,让我们从终端启动后端:
然后,在新的终端窗口中启动前端:
现在,在浏览器中导航到 http://localhost:5173 并开始聊天!
您可以打开多个浏览器选项卡来模拟多个用户,或使用 ngrok 等服务与您的朋友共享应用程序并与他们实时聊天。
在本教程中,您了解了如何快速创建可处理实时数据的完全响应式应用程序。 Svelte 可以轻松更新 DOM,而 Couchbase 可以让您在几秒钟内开始创建和存储消息。
Svelte 在竞争激烈的 Web 框架领域迅速受到赞赏和欢迎的原因有很多。 Couchbase 作为数据后端,与 Svelte 相结合,大大提高了您构建和实现的潜力。无需定义复杂的模式,如果您希望实现数据缓存或搜索功能,也无需在以后添加更多依赖项,这一切都与 Couchbase 一起内置,并且开箱即用。
剩下的唯一问题是:接下来你要构建什么?
免费开始使用 Couchbase Capella。
以上是与 Svelte 快速同步的详细内容。更多信息请关注PHP中文网其他相关文章!