学习使用React和Electron一次构建自己的桌面聊天应用程序

南门峰
2023-12-01

by Alex Booker

通过亚历克斯布克

学习使用React和Electron一次构建自己的桌面聊天应用程序 (Learn to build your own desktop chat app with React and Electron, one step at a time)

This tutorial was written in collaboration with the awesome Christian Nwamba.

本教程是与令人敬畏的Christian Nwamba合作编写的。

When learning to code, you have a bunch of resources at your disposal — books, screencasts, tutorials, even exercises. But to become a great developer, you need to practice what you learn with a project.

学习编码时,您可以使用大量资源-书籍,截屏视频,教程甚至练习。 但是要成为一名出色的开发人员,您需要练习如何通过项目来学习。

Learning by doing is the motivation for this article. You’ll start from nothing and build a complete chat application, step by step.

边干边学是本文的动机。 您将从零开始,逐步构建一个完整的聊天应用程序。

You’ll build the project one step at a time and to test you understand it, we included some special bonus challenges at the end. Are you up to the test?

您一次将构建一个项目,并测试您是否理解它,最后我们还包括一些特殊的奖金挑战。 您要接受考试吗?

Here’s what we’ll build:

这是我们要构建的:

Pretty cool, right ??

很酷吧?

When you follow along, you’ll learn how to build realtime chat, a “who’s online” list and along the way, how to structure a React app. To power our chat, we’ll be using a service I am helping to build called Chatkit.

当您继续学习时,您将学习如何建立实时聊天,“谁在线”列表,以及如何构建React应用。 为了增强我们的聊天功能,我们将使用一种我正在帮助构建的服务,称为Chatkit

Sound good? Tune in to FreeCodeCamp radio for some smooth, gentle background music to keep focused and let’s go!

听起来不错? 收看FreeCodeCamp广播,获取一些平稳,柔和的背景音乐,以保持专注并开始吧!

你需要知道的 (What you need to know)

Actually, one more thing ?:

其实还有一件事吗?:

It would be nice if you knew some basic JavaScript, Node and React already. That being said, if you don’t feel comfortable with these technologies, have a go anyway!

如果您已经了解一些基本JavaScript,Node和React,那就太好了。 话虽这么说,如果您对这些技术不满意,那就去吧!

We intentionally structured this tutorial to make it clear where to paste code so you can follow along. If you have questions, drop them here!

我们故意设计了本教程,以使您清楚地将代码粘贴到哪里,以便您可以继续学习。 如果您有任何疑问,请将其放在这里!

Alright, step one:

好吧,第一步:

设置电子 (Setup Electron)

To build a cross-platform desktop app with web technologies, we’ll use Electron.

要使用网络技术构建跨平台的桌面应用程序,我们将使用Electron

To get us off the ground, we made a minimal starter template. Download it:

为了使我们起步,我们制作了一个最小的入门模板。 下载它:

git clone https://github.com/pusher/electron-desktop-starter-template electron-desktop-chat
cd electron-desktop-chat

And install those local dependencies:

并安装这些本地依赖项:

npm install

创建一个Chatkit帐户 (Create a Chatkit account)

We’re not too concerned with building a back-end in this tutorial so we’ll use Chatkit.

在本教程中,我们不太在意构建后端,因此我们将使用Chatkit

To follow along, create a free account and a new instance called “Electron desktop chat”:

接下来, 创建一个免费帐户和一个名为“ Electron桌面聊天”的新实例:

In the settings window, turn on the test token provider:

在设置窗口中,打开测试令牌提供程序:

Note Your Test Token Provider Endpoint, Instance Locator and Secret Key. We’ll need them in the next step.

注意您的测试令牌提供者端点实例定位符秘密密钥 。 下一步,我们将需要它们。

设置节点服务器 (Setup the Node server)

Chatkit has two fundamental concepts: Users and rooms.

Chatkit有两个基本概念: 用户房间

Users can create rooms, join them, and chat in them. But before a user can interact with a room, we need to create one.

用户可以创建房间,加入房间并在其中聊天。 但是在用户可以与房间互动之前,我们需要创建一个房间。

This has to happen on the server.

这必须在服务器上发生。

In electron-desktop-chat, run:

在电子桌面聊天中,运行:

npm install --save express cors body-parser pusher-chatkit-server

And paste this in a new file called server.js:

并将其粘贴到名为server.js的新文件中:

Remember to replace instanceLocator and key with your own the Instance Locator and Key.

记住要用您自己的Instance LocatorKey替换instanceLocator和key。

Most of this code is boilerplate, importing dependencies, setting up Express, and so on.

这些代码大部分是样板文件,导入依赖项,设置Express等。

The important part is the “/users” route which handles requests to create a new user.

重要的部分是“ /用户”路由,该路由处理创建新用户的请求。

Run the server with node server.js and you will see the server is “Running on port 3001”.

使用node server.js运行服务器,您将看到服务器正在“在端口3001上运行”。

创建用户名表格 (Create the username form)

When someone loads our app, we’ll want to ask them for a username and then send it to “/users”.

当有人加载我们的应用程序时,我们将要求他们提供用户名,然后将其发送给“ / users”。

Install some native-looking UI components with:

使用以下命令安装一些具有本机外观的UI组件:

npm install --save react-desktop

And create a form component called UsernameForm:

并创建一个名为UsernameForm的表单组件:

You can read more about React form components here. By chance, the documentation uses a NameForm class similar to ours so it should all be familiar!

您可以在此处阅读更多有关React表单组件的信息 。 偶然地,文档使用与我们类似的NameForm类,因此应该都熟悉!

Next, replace all of App with:

接下来,将所有应用替换为:

And to test it, run npm run dev. You will see the username form is rendered:

要测试它,请运行npm run dev 。 您将看到呈现用户名表单:

Make sure server is running (remember, the command is`node server.js), hit Submit, and you will see that a user is created:

确保服务器正在运行(请记住,命令是node server.js ),单击Submit ,您将看到已创建用户:

在没有库的情况下转换屏幕 (Transitioning screens without a library)

Once we have a user, we can transition them from the UsernameForm to the actual chat screen. We should define that now.

有了用户后,我们可以将其从UsernameForm转换为实际的聊天屏幕。 我们现在应该定义它。

Create a new component called Chat:

创建一个名为Chat的新组件:

And update App:

并更新应用程序:

Run the app, enter a username, and you will transition to the chat screen:

运行应用程序,输入用户名,然后您将切换到聊天屏幕:

使用Chatkit添加实时聊天 (Add realtime chat with Chatkit)

Things are really coming along, wouldn’t you say?

事情真的来了,你不说吗?

To connect to Chatkit from the client, you need to install @pusher/chatkit:

要从客户端连接到Chatkit,您需要安装@ pusher / chatkit

npm install --save add @pusher/chatkit

And replace all of Chat with:

并将所有Chat替换为:

Remember to replace the tokenProviderUrl and instanceLocator values with Your Test Token Provider Endpoint and Instance Locator.

请记住用您的测试令牌提供者端点实例定位符替换tokenProviderUrlinstanceLocator值。

Run the app, hit ⌘+⌥+I (Control+Shift+I) and you will see that you connected to Chatkit.

运行该应用程序,按⌘+⌥+ I(Control + Shift + I),您将看到已连接到Chatkit。

创建聊天室 (Create a Chatkit room)

We have a user but now we need a room!

我们有一个用户,但现在我们需要一个房间!

To create one, use the Chatkit inspector:

要创建一个,请使用Chatkit检查器:

Remember to copy your room ID, we’ll need this in the next step.

记住要复制您的房间ID,下一步将需要此ID。

创建聊天室组件 (Create a chat room component)

Now we have a room, we can subscribe to new messages sent in that room.

现在我们有了一个房间,我们可以订阅在该房间中发送的新消息。

To render them, create a MessageList component:

要渲染它们,请创建一个MessageList组件:

And update Chat:

并更新聊天:

As ever, remember to update roomId with your actual room ID.

与以往一样,请记住用您的实际房间ID更新roomId

Now, when messages are sent in our room, onNewMessage will be called. From here, we can update our state and in turn, our UI.

现在,当消息发送到我们的房间时,将调用onNewMessage 。 从这里,我们可以更新状态,然后更新我们的UI。

In a second, we will let users send their own messages. For now, to test the subscription, use the inspector:

稍后,我们将让用户发送自己的消息。 现在,要测试订阅,请使用检查器:

传送讯息 (Sending messages)

To let users send their own messages, create a SendMessageForm component:

要让用户发送自己的消息,请创建一个SendMessageForm组件:

And update Chat:

并更新聊天:

Reload the app with ⌘+R (Control+Shift+R) and you will be able to send messages:

用⌘+ R(Control + Shift + R)重新加载应用程序,您将能够发送消息:

In fact, why not open two applications side-by-side and have a conversation with yourself?

实际上,为什么不并排打开两个应用程序并与自己进行对话呢?

What a time to be alive…

多么活着的时间...

设置界面样式 (Style the UI)

Thanks to React Desktop, our app already looks decent but we can do better.

感谢React Desktop ,我们的应用程序看起来已经不错了,但是我们可以做得更好。

Let’s make a few tweaks and define our layout for use in the next and final step.

让我们进行一些调整,并定义我们的布局以供下一步和最后一步使用。

Replace all of index.css with:

将所有index.css替换为:

显示谁在线 (Show who’s online)

To finish our chat app, we will add a “who’s online” list to show, you guessed it, who’s online!

要完成我们的聊天应用程序,我们将添加一个“谁在线”列表,以显示您猜到了谁在线!

Create an OnlineList component:

创建一个OnlineList组件:

Then update Chat:

然后更新聊天:

Were you expecting that to be more difficult? I definitely did the first time I tried!

您是否希望这会更加困难? 我绝对是第一次尝试!

Because Chatkit updates the users property dynamically, we don’t have to manage any of our own state. We simply need to tell React to re-render and, in turn, re-evaluate users each time someone comes online ( onUserCameOnline ), goes offline (onUserWentOffline) or joins the room (onUserJoined).

因为Chatkit动态更新了users属性,所以我们不必管理自己的任何状态。 我们只需要告诉React重新渲染,然后每次有人上线( onUserCameOnline ),下线( onUserWentOffline )或加入会议室( onUserJoined )时重新评估users

Go ahead, run the server and client and admire your magnificent new chat app:

继续,运行服务器和客户端,欣赏您壮观的新聊天应用程序:

If you’ve come this far, you might as well keep going ?! Have a stab at these bonus challenges…

如果您走了这么远,不妨继续前进!! 刺杀这些奖金挑战……

挑战1:显示房间中谁在积极打字 (Challenge 1: Show who in the room is actively typing)

See if you can add typing indicators the app. For example, if am typing, you and everyone else in the room would see “Booker is typing…”.

查看是否可以在应用程序中添加打字指示符。 例如,如果您正在打字,您和房间中的其他所有人都会看到“ Booker正在打字……”。

If Chris and I were both typing, you would see “Booker and Chris are typing…” and so on.

如果Chris和我都在打字,您会看到“ Booker和Chris在打字……”,依此类推。

Hints:

提示:

挑战2:允许用户创建自己的房间 (Challenge 2: Allow the user to create their own room)

In this tutorial, we used the inspector to create a room and then hard-coded the room ID. This isn’t a good practice.

在本教程中,我们使用检查器创建了一个房间,然后对房间ID进行了硬编码。 这不是一个好习惯。

In most applications, you would want to dynamically create rooms with the createRoom function.

在大多数应用程序中,您需要使用createRoom函数动态创建房间。

When someone loads the app, ask them for a room name as well:

当某人加载该应用程序时,还要求他们提供房间名称:

If the room exists, join it; if not, create it then join it.

如果房间存在,请加入; 如果没有,请创建它,然后加入它。

Hints:

提示:

结论 (Conclusion)

That was fun! We built a pretty cool chat app in what, less than an hour?

那很有趣! 我们用不到一个小时的时间构建了一个非常酷的聊天应用程序?

One thing I noticed (and maybe you did too) is that once the foundation is in place (template, Chatkit connection, and so on), adding new chat features is pretty simple.

我注意到的一件事(也许您也这样做了)是,一旦基础就位(模板,Chatkit连接等),添加新的聊天功能就非常简单。

Aside from the challenges, we would be curious to see where else you could take the application. Some ideas:

除了挑战之外,我们很想知道您还可以将应用程序带到哪里。 一些想法:

  • Send files

    发送文件
  • Unread message count

    未读邮件数
  • Notifications

    通知事项
  • Read cursors

    读取游标
  • Private one-to-one messaging

    私人一对一消息传递

Feel free to follow us on Twitter, @bookercodes and @codebeast.

随时在Twitter, @ bookercodes@codebeast上关注我们。

Until next time, ciao.

直到下次,再见。

翻译自: https://www.freecodecamp.org/news/build-a-desktop-chat-app-with-react-electron-and-chatkit-744d168e6f2f/

 类似资料: