🔍 搜尋結果:todo

🔍 搜尋結果:todo

我又建立了另一個 JavaScript 框架

**現在是 2024 年,您又建立了另一個 JavaScript 框架。說真的,夥計!** 當您談論另一個 Javascript 框架時,您可能會笑並認為有大量經過驗證的選項,為什麼還要建立另一個框架? 🤷‍♂️ 讓我與您分享我的個人故事,它導致了新的 Javascript 框架的發展。但如果你不關心我的可悲的故事,這裡是 TLDR: > **TiniJS**是一個元框架,由基於 Google [Lit](https://lit.dev/)庫的**Web 元件**技術提供支援。 > 您可以先下載[入門範本](https://github.com/tinijs/bare-starter)或使用 CLI 初始化應用程式,執行`npx @tinijs/cli@latest new my-app`並按照說明進行操作。 > 有關更多詳細訊息,請參閱下面的**“入門”**部分或存取<https://tinijs.dev/> 。 故事 -- ![Javascript 框架太多](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kwi99az05w9syfgn7833.jpeg) 開個玩笑吧,我不是 Javascript 的專家,但我想稍微介紹一下我的背景,這樣您可能就會知道我關於前端 Web 開發的煩惱故事。我曾經是 Angular 1 版本的開發人員,目前主要使用 Vue,偶爾使用 jQuery。我有這**3 個 PITA** (Pain In The \*beep\*)經歷,這促使我嘗試使用 TiniJS 框架。 > **PITA #1 - 建立良好的 UI/UX 很困難,既乏味又耗時!** 早在 2010 年左右,就有兩種不同類型的網站:一種有大量文本、連結,幾乎沒有一些圖片;另一種有大量文本、連結,幾乎沒有一些圖片。其他的則包含大量的圖形元素,例如 GIF 圖像、Flash 背景、彩虹遊標… 人們往往有**後端難前端容易的**刻板印象。這有點正確,但不完全正確,我的意思是,我該怪誰,對吧?因為只要有一點 HTML 和 CSS 知識,您就可以非常輕鬆地建立靜態網站。但是,為了建立良好的 UI/UX,還有很多事情需要考慮。你必須成為更多事情的大師,而它們一點也不容易! ![前端開發不容易!](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/77sp9asranurm9xcldl5.png) > **PITA #2 - CSS 框架缺乏功能並且自訂它們不是很有效!** 人們意識到前端開發的困難,開始建立CSS框架來幫助解決這個問題。 Bootstrap是這一趨勢的先驅之一,其他流行的有:Foundation、Semantic UI、Bulma、Skeleton、Pure CSS…這些CSS框架很棒,毫無疑問,它們幫助我們建立一個好的UI/使用者體驗更快,但它們也有自己的限制。 首先,儘管所有框架都提供了一定的方式來定制樣式,但總的來說,我覺得這對我來說不是很容易和可重用。 ![客製化CSS框架效率不是很高](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2lhj75s0sy977e8d5e48.jpg) 二是功能缺失。我的意思是,它們主要是 CSS,它們提供一些功能,通常是作為 JQuery 的插件。大多數情況下,您必須編寫自己的 Javascript 才能使功能正常運作。 > **PITA #3 - JavaScript 框架勢不可擋,而且有點多餘!** 進入現代 Web 開發時代,Javascript 框架已成為新趨勢。但問題是我們有太多的選擇,這既是福也是禍。它們提供了很棒的功能,但互通性不太好,您不能只從一個框架中取出一段程式碼並在另一個框架中使用它。特別是,為特定框架建立一個具有單獨套件的 UI 系統是一項非常艱鉅的任務。 ![前端 Web 開發是碎片化的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4cx44vzf0guksn2horak.png) 每次我開始一個專案或做某種前端工作時,前端web的碎片化對我來說都有些痛苦。這似乎就是生活方式,無可避免,不是嗎?請不要誤會我的意思,我並不反對任何框架,我傾向於選擇解決方案而不是技術,所以如果它適合你,就用它吧。但我想知道有什麼辦法可以以某種方式統一或縮小前端開發經驗的差距嗎? 🤔 介紹 TiniJS --------- 這就是我嘗試**TiniJS 框架**一段時間的原因。它是基於[Lit](https://lit.dev/)庫、使用本機**Web 元件**技術開發 Web/桌面/行動應用程式的工具集合。感謝[Lit](https://lit.dev/)團隊建立了一個出色的工具,幫助我們更輕鬆地使用標準 Web 元件。 它的目標是盡可能**標準化、小型化和多功能化**。與其他框架和元框架沒有真正的可比性,但總體而言,它具有相似的功能,但另一方面也有關鍵的區別。它既是替代選擇,也是對其他框架的補充。您可以使用 TiniJS 建立各種類型的應用程式:**登陸頁面、SPA、PWA、桌面應用程式、行動應用程式**…就功能而言,任何在 Javascript 中工作的內容都應該在 TiniJS 應用程式中正常運作。 整個系統由幾個部分組成,這是一個快速介紹。 > 請注意,**並非所有部件現在都可用**,該專案還處於早期階段,有些是**之前的實驗**,我盡力盡快將它們投入使用。但我的時間和資源有限,所以請耐心等待,如果可能的話請幫助我。 🙇‍♂️ > V1 的計畫及其路線圖可在<https://github.com/tinijs/tinijs>找到 ### 核 **TiniJS 的**核心提供了傳統的專案結構和簡化的開發流程。有**用於組織內容的資料夾**,**用於開發的本機伺服器**,在分發時,您可以選擇 Vite 或 Parcel 或 Webpack 來**建立產品**。 核心還包括:用於在頁面之間導航的**路由器**、用於全域狀態管理的簡單**儲存**、支援**PWA** ,... 您可以嘗試[Try TiniJS 中的範例專案(範例照片庫應用程式)](https://stackblitz.com/edit/try-tinijs?file=app%2Fapp.ts) ### 使用者介面系統 TiniJS 有一個專用的**UI 庫,我的目標是提供每個常用的元件和區塊甚至整個頁面**。元件以特殊的方式建置,它們是自訂元素,不僅可以與 TiniJS 一起使用,還可以與其他框架或不使用框架一起使用。 ![保持UI概念](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rshg9gol388nf0gsw1jt.png) 使用可重複使用元件很容易,通常是以將 props 傳遞給自訂元素標籤的形式。自訂可以透過 props 或 CSS `::part()`或自訂主題系列或完全克隆元件來源來完成,... 元件還能夠以盡可能小的努力適應幾乎所有設計系統。這是透過主題系統實現的,概念是這樣的: - 元件**只寫一次**,它們是**無頭的**(沒有特定的樣式) - 主題被組織成**系列**(又稱設計系統),系列定義自己的基本特徵,例如:Bootstrap、Material、Fluent、Spectrum,... - 根據基本特徵,一個系列有風格變體,稱為**“皮膚”** ,例如,Bootstrap 系列可能有:淺色皮膚、深色皮膚… 考慮到主題概念,任何應用程式都可以具有以下主題功能: - **一個**主題系列 - 可能是當今存在的所有網路應用程式中的 80% 到 90%,只有 1 種特定風格相當於 TiniJS 1 主題系列。 - **一個**主題系列 + 多個皮膚 - 常見的用例是亮/暗模式,相當於 TiniJS 1 主題系列,具有來自同一系列的多個皮膚。 - **多個**主題系列 - 高度個人化的應用程式可能有多個主題系列,每個系列都有一個或多個皮膚,將根據使用者參考應用某個主題。 UI 使用詳細資訊將在[主頁](https://tinijs.dev/ui)上提供,現在您也可以在<https://ui.tinijs.dev/>查看實驗概念,以查看該概念的實際應用。 ### 網頁、PWA、混合桌面/行動設備 預設的 TiniJS 應用程式是**單頁應用程式**,它小而快速,可以直接部署為 Web 應用程式。但是,您也可以將 TiniJS 轉換為以下一種或所有類型的應用程式: - **漸進式 Web 應用程式**(PWA) - 使用單一 CLI 命令實作(即將推出) - 混合**桌面/行動**應用程式 - 使用 Tauri 2.0 或類似工具(todo:編寫指令) ### 靜態和伺服器 TiniJS 應用程式可以作為靜態網路啟動,無論大小,無需伺服器或資料庫。您始終可以使用 SaaS 服務來滿足幾乎任何後端需求。我還在開發`@tinijs/content` - 一個基於文件的內容管理系統,用於輕鬆管理多種類型的內容。靜態站點產生(SSG)或預渲染也在計劃中。 如果您需要處理後端任務並參考從 Node 伺服器而不是靜態主機為 Web 應用程式提供服務,則可選的 Nitro 伺服器用於**伺服器/API 路由**和其他**伺服器內容**。我的開發能力有限,因此第一個版本可能不支援伺服器端渲染(SSR),相反,我計劃使用半SSR,其中伺服器將為用戶提供單頁服務,並向機器人提供最少的伺服器端渲染內容。 ### 功能和模組 在功能方面,由於 TiniJS 應用程式**基於標準 Web 技術**,因此在瀏覽器中工作的任何程式庫和功能都可能在 TiniJS 應用程式中運作。因此,與其他框架相比,您可能**不必擔心功能**。您甚至可以在 TiniJS 應用程式中使用其他框架,例如初始化 Vue 應用程式並將其安裝到 TiniJS 頁面內的元素。 還有一個模組架構師,以便某些模組可以進入 TiniJS 應用程式的工作流程,建立更簡化的開發管道。 ### 工具 官方 CLI 工具提供了一些使用 TiniJS 應用程式的便利命令。 - `dev` - 啟動本機開發伺服器 - `build` - 建構生產分配 - `preview` - 在部署之前預覽生產版本 - `generate` - 生成元件、頁面、實用程式... 此外,CLI**足夠通用,可以在 TiniJS 應用程式以外的任何類型的專案中使用**。它具有可擴展的架構,您可以在其中擴展更多命令以用於其他自動化任務。一些官方擴展,例如`ui`命令(來自`@tinijs/ui` )用於處理 UI 任務或`content`命令(來自`@tinijs/content` )用於處理內容相關任務,...您可以根據自己的目的建立 CLI 擴展包私人或共享。 好了,說得夠多了,讓我看看一些行動吧! 👌 開始使用 ---- **Tini** (越南語中的“ [Tí nị](https://translate.google.com/?sl=vi&tl=en&text=t%C3%AD%20n%E1%BB%8B&op=translate) ”,意思是非常小、可愛的東西)。 為了快速建立**TiniJS**專案,您可以使用[CLI](https://tinijs.dev/cli)來初始化模板。 ``` npx @tinijs/cli@latest new my-app ``` 上面的命令透過下載**Bare**模板來建立一個應用程式。將來,我想提供幾個入門範本。您還可以建立自己的模板並與社區共享或供您自己私人使用。目前,這些模板可用: - [Bare](https://github.com/tinijs/bare-starter) (預設)- TiniJS 應用程式的最小結構。 - [空白](https://github.com/tinijs/blank-starter)(標誌`-t blank` )- 包含路由器、狀態管理、元標記管理和[Bootstrap 主題系列](https://tinijs.dev/ui)。 現在,在專案內部,您可以執行`npm run dev`來啟動開發伺服器。您可以透過編輯檔案`./app/app.ts`來開始開發,該檔案是應用程式的根元件。有關如何使用 Lit 處理自訂元素,請存取[Lit 元件](https://lit.dev/docs/components/overview/), `LitElement`和`TiniComponent`之間存在一些差異,但現在您可以像平常一樣修改`static styles`和`render()` 。 若要建立發行版,請執行`npm run build`並可選擇執行`npm run preview`以預覽生產版本。現在您可以將`.output`資料夾部署到任何靜態主機。 您可能需要查看這些範例以了解 TiniJS 應用程式如何運作的更多細節。 - 首頁 - <https://github.com/tinijs/tinijs/tree/main/apps/tinijs.dev> - 待辦事項應用程式 - <https://github.com/tinijs/tinijs/tree/main/examples/todo> 這就是**TiniJS 框架**的基本介紹。下次我們將探索**TiniJS 應用程式的結構並使用元件**。 欲了解更多訊息,請存取: <https://tinijs.dev> 謝謝您,編碼愉快! 💖 --- 原文出處:https://dev.to/lamnhan/ive-created-yet-another-javascript-framework-5c5o

我的新開源儲存庫可安排您的所有內容!

你好! 幾年前,我分享了我關閉之前的新創公司並將[其開源](https://dev.to/nevodavid/i-turned-my-startup-into-open-source-4efh)的故事。 從那時起,我就在開源通知基礎設施 Novu 工作,實際上我學到了很多關於開源社群的力量。 我在 DEV 上寫了 74 篇帖子,產生了**1,182,911 次瀏覽**🤗 這使得 Novu 成為最受歡迎的開源儲存庫之一**(31k 星)** --- 我開始談論它 ------ 我建立了一份名為[Gitroom](https://gitroom.com/) (以前稱為GitHub20k)的時事通訊,並寫下了我在這一年中所做的一切,從在DEV 上發布實際價值教程到使用有影響力的人推廣存儲庫。 我每月與 30 多名開源維護者交談!幫助他們了解其儲存庫。 但有一件事情我一直沒有解決。 我的戰術壓力很大。不是隨意寫文章。 但我在正確的時間寫了它們,並在不同的 Reddit 和社交媒體管道上推廣它們。 問題是你的發佈在文章發表之前就被卡住了——你無法為任何事情計時,所以你必須在一周內完成。 如果其他人參與發布,事情就會變得很困難;我曾經錯過了很多。因此,我決定建立 Gitroom 平台。 --- Gitroom 平台 ---------- Gitroom 平台是安排開源發布的最佳工具。它是 100% 開源的!在這裡檢查並加註星標。 https://github.com/gitroomhq/gitroom ### 技術堆疊 - NextJS(順風) - NestJS ### 分析 從基礎知識開始,我想知道: - 表現最好的一天是什麼時候(關於星星的數量),然後將其與我所做的發布週進行交叉引用。 - 了解我何時在 GitHub 上流行(收到通知) - 了解 GitHub feed 何時刷新,以便相應地安排我的內容。 ![](https://media.beehiiv.com/cdn-cgi/image/fit=scale-down,format=auto,onerror=redirect,quality=80/uploads/asset/file/9f313fa8-7f32-4cad-9d24-97560905eeb2/CleanShot_2024-03-16_at_15.14.48_2x.png?t=1710576917) ### 啟動頁面 要啟動,您需要: - 將所有管道用於開源,從Reddit等社交媒體到[DEV.to](http://DEV.to?utm_source=nevo.github20k.com&utm_medium=referral&utm_campaign=the-gitroom-platform-is-live)等文章發布 - 請參閱下次刷新的時間表,以便我可以相應地進行計劃。 - 在發布之前加入評論並與我的團隊合作。 ![](https://media.beehiiv.com/cdn-cgi/image/fit=scale-down,format=auto,onerror=redirect,quality=80/uploads/asset/file/9b4efadf-891f-454f-9afd-81c169c2912e/CleanShot_2024-03-16_at_15.21.35.gif?t=1710577390) ### 時間表頁面 這就是魔法發生的地方: - 您可以同時**交叉發佈**到多個頻道(例如 DEV、Hashnode 和 Medium) - 您可以發佈到更複雜的頻道,例如 Reddit,您必須在其中定義**天賦**和 subreddit。 - 您可以全域編輯所有內容,然後切換到特定頻道。 - 查看它在現有頻道中的外觀預覽。 - 在發布之前**使用之前預定帖子的連結**!您也可以將其用作規範連結! ![](https://media.beehiiv.com/cdn-cgi/image/fit=scale-down,format=auto,onerror=redirect,quality=80/uploads/asset/file/d8ac54a6-d9a7-4219-a17f-40b9c3692928/CleanShot_2024-03-16_at_15.30.43.gif?t=1710578073) 社區的未來! --- 這是 Gitroom 的第一個版本,主要用於規劃您的發布。**這是您應該期待的:** - 交換或購買其他社區成員和影響者的帖子!**是的**!有影響力的人將為您建立帖子,它們將出現在時間軸上。什麼是最好的事?他們只有在貼文發布後才會獲得報酬(良好的激勵措施) - 成為 OSS 朋友的一部分,這是一個列出系統中所有開源公司的 API -**非常適合 SEO。** - 加入推薦並與其他開源朋友一起**“使用”** ! 並且: - **從Notion等其他平台匯入**——我所有的部落格文章都是我自己在Notion上寫的,但每次複製時,我都需要手動上傳所有圖片。 - 有更多可供安排的頻道,例如 Discord 和 Mastodon。 - 自動交叉發布(如果你不想使用 Gitroom 調度程式) - 媒體生成器,例如您擁有的星星數量。 --- 幫幫我! 🤗 這是一個新專案,100% 開源(同類中的第一個!) 你能給我的任何星星都會幫助我更成長❤️ https://github.com/gitroomhq/gitroom 在這裡加註星標❤️ --- 原文出處:https://dev.to/github20k/my-new-open-source-repository-to-schedule-all-your-content-2f2a

使用這些 React 函式庫和雲端後端來建立全端應用程式。

今天,我們將學習如何使用 Wing 作為後端建立全端應用程式。 ![反應 + 維特 + 翅膀](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vb7jf7dk9b08x042p0vl.png) 我們將使用 React 和 Vite 作為前端。 我知道還有其他框架,如 Vue、Angular 和 Next,但 React 仍然是最常見的,並且迄今為止有大量值得信賴的新創公司使用它。 如果您不知道, [React](https://github.com/facebook/react)是 Facebook 建立的開源程式庫,用於建立 Web 和本機使用者介面。正如您從儲存庫中看到的,它被超過 2040 萬開發人員使用。所以,這是值得的。 讓我們看看如何使用 Wing 作為後端。 ![豎起大拇指](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pskz2tyzodt4wnxbqa8y.gif) --- [Wing](https://git.new/wing-repo) - 一種雲端程式語言。 --------------------------------------------- ![翅膀](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n97bowkrexjk46n94bcc.png) Winglang 是一種專為雲端(又稱「面向雲端」)設計的新型開源程式語言。它允許您在雲端中建立應用程式,並且具有相當簡單的語法。 Wing 程式可以使用功能齊全的模擬器在本地執行(是的,不需要網路),也可以部署到任何雲端供應商。 ![機翼基礎設施](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eun3zd1gkp870rj57eeu.png) Wing 需要 Node `v20 or higher` 。 建立一個父目錄(我們使用的`shared-counter` )並使用 Vite 使用新的 React 應用程式設定前端。您可以使用這個 npm 指令。 ``` npm create -y vite frontend -- --template react-ts // once installed, you can check if it's running properly. cd frontend npm install npm run dev ``` 您可以使用此 npm 命令安裝 Wing。 ``` npm install -g winglang ``` 您可以使用`wing -V`驗證安裝。 Wing 還提供官方[VSCode 擴充功能](https://marketplace.visualstudio.com/items?itemName=Monada.vscode-wing)和[IntelliJ](https://plugins.jetbrains.com/plugin/22353-wing) ,後者提供語法突出顯示、補全、轉到定義和嵌入式 Wing 控制台支援。您可以在建立應用程式之前安裝它! 建立後端目錄。 ``` mkdir ~/shared-counter/backend cd ~/shared-counter/backend ``` 建立一個新的空 Wing 專案。 ``` wing new empty // This will generate three files: package.json, package-lock.json and main.w file with a simple "hello world" program wing it // to run it in the Wing simulator // The Wing Simulator will be opened in your browser and will show a map of your app with a single function. //You can invoke the function from the interaction panel and check out the result. ``` 使用指令`wing new empty`後的結構如下。 ``` bring cloud; // define a queue, a bucket, and a counter let bucket = new cloud.Bucket(); let counter = new cloud.Counter(initial: 1); let queue = new cloud.Queue(); // When a message is received in the queue -> it should be consumed // by the following closure queue.setConsumer(inflight (message: str) => { // Increment the distributed counter, the index variable will // store the value before the increment let index = counter.inc(); // Once two messages are pushed to the queue, e.g. "Wing" and "Queue". // Two files will be created: // - wing-1.txt with "Hello Wing" // - wing-2.txt with "Hello Queue" bucket.put("wing-{index}.txt", "Hello, {message}"); log("file wing-{index}.txt created"); }); ``` 您可以安裝`@winglibs/vite`來啟動開發伺服器,而不是使用`npm run dev`來啟動本機 Web 伺服器。 ``` // in the backend directory npm i @winglibs/vite ``` 您可以使用`backend/main.w`中提供的 publicEnv 將資料傳送到前端。 讓我們來看一個小例子。 ``` // backend/main.w bring vite; new vite.Vite( root: "../frontend", publicEnv: { TITLE: "Wing + Vite + React" } ); // import it in frontend // frontend/src/App.tsx import "../.winglibs/wing-env.d.ts" //You can access that value like this. <h1>{window.wing.env.TITLE}</h1> ``` 你還可以做更多: - 讀取/更新 API 路線並使用 Wing Simulator 檢查它。 - 使用後端獲取值。 - 使用`@winglibs/websockets`同步瀏覽器,它在後端部署一個 WebSocket 伺服器,您可以連接此 WebSocket 來接收即時通知。 您可以閱讀完整的逐步指南,以了解[如何使用 React 作為前端和 Wing 作為後端建立簡單的 Web 應用程式](https://www.winglang.io/docs/guides/react-vite-websockets)。測試是使用 Wing Simulator 完成的,並使用 Terraform 部署到 AWS。 部署後的AWS架構是這樣的。 ![建築學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/27awil840ktgh3jvklij.png) 為了提供開發者選擇和更好的體驗,Wing 推出了對[TypeScript (Wing)](https://www.winglang.io/docs/typescript/)等其他語言的全面支援。唯一強制性的事情是您必須安裝 Wing SDK。 這也將使控制台完全可用於本地偵錯和測試,而無需學習 Wing 語言。 Wing 甚至還有其他[指南](https://www.winglang.io/docs/category/guides),因此更容易遵循。 ![指南](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/31czxehkg10ezmlpf7ac.png) 您可以閱讀[文件](https://www.winglang.io/docs)並查看[範例](https://www.winglang.io/docs/category/examples)。 您也可以在[Playground](https://www.winglang.io/play/?code=LwAvACAAVABoAGkAcwAgAGkAcwAgAHQAaABlACAAaQBtAHAAbwByAHQAIABzAHQAYQB0AGUAbQBlAG4AdAAgAGkAbgAgAFcAaQBuAGcALgAKAC8ALwAgAEgAZQByAGUAIAB3AGUAIABiAHIAaQBuAGcAIAB0AGgAZQAgAFcAaQBuAGcAIABzAHQAYQBuAGQAYQByAGQAIABsAGkAYgByAGEAcgB5ACAAdABoAGEAdAAgAAoALwAvACAAYwBvAG4AdABhAGkAbgBzACAAYQBiAHMAdAByAGEAYwB0AGkAbwBuAHMAIABvAGYAIABwAG8AcAB1AGwAYQByACAAYwBsAG8AdQBkACAAcwBlAHIAdgBpAGMAZQBzAC4ACgBiAHIAaQBuAGcAIABjAGwAbwB1AGQAOwAKAAoALwAvACAAVABoAGkAcwAgAGMAbwBkAGUAIABkAGUAZgBpAG4AZQBzACAAYQAgAGIAdQBjAGsAZQB0ACAAYQBzACAAcABhAHIAdAAgAG8AZgAgAHkAbwB1AHIAIABhAHAAcAAuAAoALwAvACAAVwBoAGUAbgAgAGMAbwBtAHAAaQBsAGkAbgBnACAAdABvACAAYQAgAHMAcABlAGMAaQBmAGkAYwAgAGMAbABvAHUAZAAgAHAAcgBvAHYAaQBkAGUAcgAKAC8ALwAgAGkAdAAgAHcAaQBsAGwAIABiAGUAIABzAHUAYgBzAHQAaQB0AHUAdABlAGQAIABiAHkAIABhAG4AIABpAG0AcABsAGUAbQBlAG4AdABhAHQAaQBvAG4AIABmAG8AcgAKAC8ALwAgAHQAaABhAHQAIABjAGwAbwB1AGQALgAgAEkALgBlACwAIABmAG8AcgAgAEEAVwBTACAAaQB0ACAAdwBpAGwAbAAgAGIAZQAgAGEAbgAgAFMAMwAgAEIAdQBjAGsAZQB0AC4ACgBsAGUAdAAgAGIAdQBjAGsAZQB0ACAAPQAgAG4AZQB3ACAAYwBsAG8AdQBkAC4AQgB1AGMAawBlAHQAKAApADsACgAKAC8ALwAgACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAKAC8ALwAgAFkAbwB1ACAAYwBhAG4AIABpAG4AdABlAHIAYQBjAHQAIAB3AGkAdABoACAAdABoAGUAIABhAHAAcAAgAGkAbgAgAHQAaABlACAAYwBvAG4AcwBvAGwAZQAgAC0ALQA%2BAAoALwAvACAACgAvAC8AIABDAGwAaQBjAGsAIABvAG4AIAB0AGgAZQAgAEYAdQBuAGMAdABpAG8AbgAsACAAYQBuAGQAIAB0AGgAZQBuACAAaQBuAHYAbwBrAGUAIABpAHQAIABpAG4AIAB0AGgAZQAKAC8ALwAgAGwAbwB3AGUAcgAgAHIAaQBnAGgAdAAgAHAAYQBuAGUAbAAsACAAbwByACAAYwBsAGkAYwBrACAAbwBuACAAdABoAGUAIABCAHUAYwBrAGUAdAAKAC8ALwAgAHQAbwAgAHMAZQBlACAAaQB0AHMAIABjAG8AbgB0AGUAbgB0AHMAIABpAG4AIAB0AGgAZQAgAHAAYQBuAGUAbAAsACAAZQB0AGMALgAKAC8ALwAgACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAhACEAIQAKAAoALwAvACAAYABpAG4AZgBsAGkAZwBoAHQAcwBgACAAcgBlAHAAcgBlAHMAZQBuAHQAIABjAG8AZABlACAAdABoAGEAdAAgAHIAdQBuAHMAIABsAGEAdABlAHIALAAgAG8AbgAKAC8ALwAgAG8AdABoAGUAcgAgAG0AYQBjAGgAaQBuAGUAcwAsACAAaQBuAHQAZQByAGEAYwB0AGkAbgBnACAAdwBpAHQAaAAgAGMAYQBwAHQAdQByAGUAZAAgAGQAYQB0AGEAIABhAG4AZAAKAC8ALwAgAHIAZQBzAG8AdQByAGMAZQBzACAAZgByAG8AbQAgAHQAaABlACAAcAByAGUALQBmAGwAaQBnAGgAdAAgAHAAaABhAHMAZQAuAAoAbABlAHQAIABoAGUAbABsAG8AXwB3AG8AcgBsAGQAIAA9ACAAaQBuAGYAbABpAGcAaAB0ACAAKAApACAAPQA%2BACAAewAKACAAIABiAHUAYwBrAGUAdAAuAHAAdQB0ACgAIgBoAGUAbABsAG8ALgB0AHgAdAAiACwAIAAiAEgAZQBsAGwAbwAsACAAVwBvAHIAbABkACEAIgApADsACgB9ADsACgAKAC8ALwAgAEkAbgBmAGwAaQBnAGgAdABzACAAYwBhAG4AIABiAGUAIABkAGUAcABsAG8AeQBlAGQAIABhAHMAIABzAGUAcgB2AGUAcgBsAGUAcwBzACAAZgB1AG4AYwB0AGkAbwBuAHMACgBuAGUAdwAgAGMAbABvAHUAZAAuAEYAdQBuAGMAdABpAG8AbgAoAGgAZQBsAGwAbwBfAHcAbwByAGwAZAApADsACgAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAAIAAgACAACgAvAC8AIACRISAAUwB3AGkAdABjAGgAIABmAGkAbABlAHMAIABhAG4AZAAgAHMAZQBlACAAbwB0AGgAZQByACAAZQB4AGEAbQBwAGwAZQBzACAAdwBpAHQAaAAgAG0AbwByAGUACgAvAC8AIABlAHgAcABsAGUAbgBhAHQAaQBvAG4AcwAgAGEAYgBvAHYAZQAuAA%3D%3D)中使用 Wing 查看結構和範例。 如果你比較像輔導員。看這個! https://www.youtube.com/watch?v=wzqCXrsKWbo Wing 在 GitHub 上擁有超過 3500 個 Star,發布了 1500 多個版本,但仍未進入 v1 版本,這意味著意義重大。 去嘗試一下,做一些很酷的事情吧! https://git.new/wing-repo 星翼 ⭐️ --- 開發者生態系統不斷發展,許多開發者圍繞 React 建置了一些獨特的東西。 我不會介紹如何使用 React,因為這是一個非常廣泛的主題,我在最後貼了一些資源來幫助您學習 React。 但為了幫助您建立出色的 React 專案,我們介紹了 25 個開源專案,您可以使用它們來使您的工作更輕鬆。 這將有大量的資源、想法和概念。 我甚至會給你一些學習資源,以及一些產品的專案範例來學習 React。 一切都是免費的,而且只有 React。 讓我們涵蓋這一切! --- 1. [Mantine Hooks](https://www.npmjs.com/package/@mantine/hooks) - 用於狀態和 UI 管理的 React hooks。 -------------------------------------------------------------------------------------------- ![曼丁鉤子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g9gxhpt4zpmxgg2cfbqi.png) 這可能不是專門針對 React 的,但是您可以使用這些鉤子來使您的工作更輕鬆。這些鉤子隨時可用,每個鉤子都有許多選項。 如果我必須評價的話,這將是每個人都可以使用的最有用的專案,而不是從頭開始編寫程式碼。 相信我,獲得 60 多個 Hooks 是一件大事,因為他們有一個簡單的方法讓您可以透過簡單的文件查看每個 Hooks 的演示。 開始使用以下 npm 指令。 ``` npm install @mantine/hooks ``` 這就是如何使用`useScrollIntoView`作為 mantine 掛鉤的一部分。 ``` import { useScrollIntoView } from '@mantine/hooks'; import { Button, Text, Group, Box } from '@mantine/core'; function Demo() { const { scrollIntoView, targetRef } = useScrollIntoView<HTMLDivElement>({ offset: 60, }); return ( <Group justify="center"> <Button onClick={() => scrollIntoView({ alignment: 'center', }) } > Scroll to target </Button> <Box style={{ width: '100%', height: '50vh', backgroundColor: 'var(--mantine-color-blue-light)', }} /> <Text ref={targetRef}>Hello there</Text> </Group> ); } ``` 它們幾乎擁有從本地儲存到分頁、滾動視圖、交叉點,甚至一些非常酷的實用程式(例如滴管和文字選擇)的所有功能。這實在太有幫助了! ![滴管](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pighzv57fvyp5uxvw8dz.png) 您可以閱讀[文件](https://mantine.dev/hooks/use-click-outside/)。 如果您正在尋找更多選項,您也可以使用[替代庫](https://antonioru.github.io/beautiful-react-hooks/)。 他們在 GitHub 上擁有超過 23k star,但這不僅僅是為了 hooks,因為他們是 React 的元件庫。 隨著`v7`版本的發布,它的每週下載量已超過 38 萬次,這表明它們正在不斷改進且值得信賴。 https://github.com/mantinedev/mantine Star Mantine Hooks ⭐️ --- 2. [React Grid Layout](https://github.com/react-grid-layout/react-grid-layout) - 可拖曳且可調整大小的網格佈局,具有響應式斷點。 -------------------------------------------------------------------------------------------------------- ![反應網格佈局](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pyg7g1bm1d3hvkexrnh3.png) React-Grid-Layout 是專為 React 應用程式建構的響應式網格佈局系統。 透過支援可拖曳、可調整大小和靜態小部件,它提供了使用網格的簡單解決方案。 與 Packery 或 Gridster 等類似系統不同,React-Grid-Layout 不含 jQuery,確保輕量級且高效的實作。 它與伺服器渲染應用程式的無縫整合以及序列化和恢復佈局的能力使其成為開發人員在 React 專案中使用網格佈局的寶貴工具。 開始使用以下 npm 指令。 ``` npm install react-grid-layout ``` 這就是如何使用響應式網格佈局。 ``` import { Responsive as ResponsiveGridLayout } from "react-grid-layout"; class MyResponsiveGrid extends React.Component { render() { // {lg: layout1, md: layout2, ...} const layouts = getLayoutsFromSomewhere(); return ( <ResponsiveGridLayout className="layout" layouts={layouts} breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }} cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }} > <div key="1">1</div> <div key="2">2</div> <div key="3">3</div> </ResponsiveGridLayout> ); } } ``` 您可以閱讀[文件](https://github.com/react-grid-layout/react-grid-layout?tab=readme-ov-file#installation)並查看[演示](https://react-grid-layout.github.io/react-grid-layout/examples/0-showcase.html)。有一系列[演示](https://github.com/react-grid-layout/react-grid-layout?tab=readme-ov-file#demos),甚至可以透過點擊“查看下一個範例”來獲得。 您也可以嘗試[codesandbox](https://codesandbox.io/p/devbox/github/gilbarbara/react-joyride-demo/tree/main/?embed=1)上的東西。 該專案在 GitHub 上有超過 19k+ 的星星,有超過 16k+ 的開發者使用,並且[npm 套件](https://www.npmjs.com/package/react-grid-layout)的每週下載量超過 600k+。 https://github.com/react-grid-layout/react-grid-layout 明星 React 網格佈局 ⭐️ --- 3. [React Spectrum](https://github.com/adobe/react-spectrum) - 提供出色使用者體驗的程式庫和工具的集合。 ----------------------------------------------------------------------------------- ![反應譜](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b4wkgbdpd1gve36vgjne.png) React Spectrum 是一個庫和工具的集合,可幫助您建立自適應、可存取且強大的使用者體驗。 它們提供了太多的東西,以至於很難在一篇文章中涵蓋所有內容。 總的來說,他們提供了這四個庫。 ![反應譜](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m97vdq3x7nllmhyjy7p9.png) - [反應譜](https://react-spectrum.adobe.com/react-spectrum/index.html) - [React Stately](https://react-spectrum.adobe.com/react-stately/index.html) - 一組龐大的 React Hooks,為您的設計系統提供跨平台狀態管理。 - [反應詠嘆調](https://react-spectrum.adobe.com/react-aria/index.html) - [國際化](https://react-spectrum.adobe.com/internationalized/index.html) 我們將了解一些有關 React Aria 的內容,它是一個無樣式 React 元件和鉤子庫,可幫助您為應用程式建立可存取的、高品質的 UI 元件。 它經過了各種設備、互動方式和輔助技術的精心測試,以確保為所有用戶提供最佳體驗。 開始使用以下 npm 指令。 ``` npm i react-aria-components ``` 這就是建立自訂`select`的方法。 ``` import {Button, Label, ListBox, ListBoxItem, Popover, Select, SelectValue} from 'react-aria-components'; <Select> <Label>Favorite Animal</Label> <Button> <SelectValue /> <span aria-hidden="true">▼</span> </Button> <Popover> <ListBox> <ListBoxItem>Cat</ListBoxItem> <ListBoxItem>Dog</ListBoxItem> <ListBoxItem>Kangaroo</ListBoxItem> </ListBox> </Popover> </Select> ``` 相信我,出於學習目的,這是一座金礦。 ![選擇的設計結構](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ndy61o8vtjjbq78e8vl8.png) 他們使用自己強大的[40 多個樣式元件](https://opensource.adobe.com/spectrum-css/),這比通常提供的要多得多。他們也有自己的一套[設計系統,](https://spectrum.adobe.com/)例如字體、UI、版面、動作等等。 ![造型元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a047jcb2ou7h057yf2d4.png) ![造型元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y1w5jq1vfbhd6o9c9ehm.png) 您可以詳細了解[Spectrum](https://react-spectrum.adobe.com/index.html)及其[架構](https://react-spectrum.adobe.com/architecture.html)。 他們在 GitHub 上擁有超過 11,000 顆星,這表明了他們的質量,儘管他們並不廣為人知。研究它們可以為您建立圖書館提供寶貴的見解。 https://github.com/adobe/react-spectrum Star React Spectrum ⭐️ --- 4.[保留 React](https://github.com/StaticMania/keep-react) - Tailwind CSS 和 React.js 的 UI 元件庫。 ------------------------------------------------------------------------------------------- ![保持反應](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5s2z1xig75on0j2gjt1g.png) Keep React 是一個基於 Tailwind CSS 和 React.js 建立的開源元件庫。它提供了一組多功能的預先設計的 UI 元件,使開發人員能夠簡化現代、響應式且具有視覺吸引力的 Web 應用程式的建立。 開始使用以下 npm 指令。 ``` npm i keep-react ``` 這就是使用時間軸的方法。 ``` "use client"; import { Timeline } from "keep-react"; import { CalendarBlank } from "phosphor-react"; export const TimelineComponent = () => { return ( <Timeline horizontal={true}> <Timeline.Item> <Timeline.Point icon={<CalendarBlank size={16} />} /> <Timeline.Content> <Timeline.Title>Keep Library v1.0.0</Timeline.Title> <Timeline.Time>Released on December 2, 2021</Timeline.Time> <Timeline.Body> Get started with dozens of web components and interactive elements. </Timeline.Body> </Timeline.Content> </Timeline.Item> <Timeline.Item> <Timeline.Point icon={<CalendarBlank size={16} />} /> <Timeline.Content> <Timeline.Title>Keep Library v1.1.0</Timeline.Title> <Timeline.Time>Released on December 23, 2021</Timeline.Time> <Timeline.Body> Get started with dozens of web components and interactive elements. </Timeline.Body> </Timeline.Content> </Timeline.Item> <Timeline.Item> <Timeline.Point icon={<CalendarBlank size={16} />} /> <Timeline.Content> <Timeline.Title>Keep Library v1.3.0</Timeline.Title> <Timeline.Time>Released on January 5, 2022</Timeline.Time> <Timeline.Body> Get started with dozens of web components and interactive elements. </Timeline.Body> </Timeline.Content> </Timeline.Item> </Timeline> ); } ``` 輸出如下。 ![時間軸元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v22pagugp45z68jap3en.png) 流暢的小動畫讓這一切都是值得的,如果你想快速建立一個 UI,沒有任何麻煩,你可以使用它。 ![上傳](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfy9f9w0nc6ipn6wigil.png) ![通知](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5zpwcnozi5ye3wpnev1g.png) 您可以閱讀[文件](https://react.keepdesign.io/docs/getting-started/Introduction)並查看[故事書](https://react-storybook.keepdesign.io/?path=/docs/components-accordion--docs)以進行詳細的使用測驗。 該專案在 GitHub 上有超過 1000 顆星,而且它的一些元件使用起來非常方便。 https://github.com/StaticMania/keep-react Star Keep React ⭐️ --- 5. [React Content Loader](https://github.com/danilowoz/react-content-loader) - SVG 支援的元件,可輕鬆建立骨架載入。 --------------------------------------------------------------------------------------------------- ![反應內容載入器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g8g2yc0zush5vfgwo6hv.png) 該專案為您提供了一個由 SVG 驅動的元件,可以輕鬆建立佔位符載入(如 Facebook 的卡片載入)。 在載入狀態期間使用骨架來向使用者指示內容仍在載入。 總的來說,這是一個非常方便的專案,可以增強整體使用者體驗。 開始使用以下 npm 指令。 ``` npm i react-content-loader --save ``` 您可以這樣使用它。 ``` import React from "react" import ContentLoader from "react-content-loader" const MyLoader = (props) => ( <ContentLoader speed={2} width={400} height={160} viewBox="0 0 400 160" backgroundColor="#f3f3f3" foregroundColor="#ecebeb" {...props} > <rect x="48" y="8" rx="3" ry="3" width="88" height="6" /> <rect x="48" y="26" rx="3" ry="3" width="52" height="6" /> <rect x="0" y="56" rx="3" ry="3" width="410" height="6" /> <rect x="0" y="72" rx="3" ry="3" width="380" height="6" /> <rect x="0" y="88" rx="3" ry="3" width="178" height="6" /> <circle cx="20" cy="20" r="20" /> </ContentLoader> ) export default MyLoader ``` ![輸出](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xnvqlf6fmg2fayd29ojr.png) 您甚至可以拖曳單一骨架或使用為 Facebook 和 Instagram 等不同社群媒體預先定義的骨架。 您可以閱讀[文件](https://github.com/danilowoz/react-content-loader?tab=readme-ov-file#gettingstarted)並查看[演示](https://skeletonreact.com/)。 該專案在 GitHub 上擁有 13k+ Stars,並在 GitHub 上有 45k+ 開發人員使用。 https://github.com/danilowoz/react-content-loader Star React 內容載入器 ⭐️ --- 6. [React PDF](https://github.com/diegomura/react-pdf) - 使用 React 建立 PDF 檔案。 ---------------------------------------------------------------------------- ![反應 pdf](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6jd7sz8eqda09rgjpf13.png) 該套件用於使用 React 建立 PDF。 開始使用以下 npm 指令。 ``` npm install @react-pdf/renderer --save ``` 您可以這樣使用它。 ``` import React from 'react'; import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer'; // Create styles const styles = StyleSheet.create({ page: { flexDirection: 'row', backgroundColor: '#E4E4E4', }, section: { margin: 10, padding: 10, flexGrow: 1, }, }); // Create Document Component const MyDocument = () => ( <Document> <Page size="A4" style={styles.page}> <View style={styles.section}> <Text>Section #1</Text> </View> <View style={styles.section}> <Text>Section #2</Text> </View> </Page> </Document> ); ``` ![輸出](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cb5fpfzijv3g5fi5utmw.png) ![輸出pdf分頁](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f46t80n0redm14icia1r.png) 您可以閱讀[文件](https://react-pdf.org/)並查看[演示](https://react-pdf.org/repl)。 React-pdf 現在提供了一個名為`usePDF`的鉤子,可以透過 React hook API 存取所有 PDF 建立功能。如果您需要更多控製文件的呈現方式或更新頻率,這非常有用。 ``` const [instance, update] = usePDF({ document }); ``` 該專案在 GitHub 上有 13k+ Stars,有超過 270 個版本,[每週下載量超過 400k](https://www.npmjs.com/package/@react-pdf/renderer) ,這是一個好兆頭。 https://github.com/diegomura/react-pdf Star React PDF ⭐️ --- 7. [Recharts](https://github.com/recharts/recharts) - 使用 React 和 D3 建立的重新定義的圖表庫。 -------------------------------------------------------------------------------- ![重新繪製圖表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i6817tmlix6n7wtgp1yq.png) 該庫的主要目的是幫助您輕鬆地在 React 應用程式中編寫圖表。 Recharts 的主要原則是。 1. 只需使用 React 元件進行部署即可。 2. 原生 SVG 支持,輕量級,僅依賴一些 D3 子模組。 3. 聲明性元件、圖表元件純粹是表示性的。 開始使用以下 npm 指令。 ``` npm install recharts ``` 您可以這樣使用它。 ``` <LineChart width={500} height={300} data={data} accessibilityLayer> <XAxis dataKey="name"/> <YAxis/> <CartesianGrid stroke="#eee" strokeDasharray="5 5"/> <Line type="monotone" dataKey="uv" stroke="#8884d8" /> <Line type="monotone" dataKey="pv" stroke="#82ca9d" /> <Tooltip/> </LineChart> ``` ![輸出](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uqtp999q1ahq8ajmvuwf.png) 您可以閱讀[文件](https://recharts.org/en-US/guide)並查看有關[Storybook](https://recharts.org/en-US/storybook)的更多資訊。 他們提供了大量的選項來自訂它,這就是開發人員喜歡它的原因。他們也提供一般常見問題的[wiki](https://github.com/recharts/recharts/wiki)頁面。 您也可以在此處的codesandbox 上嘗試。 https://codesandbox.io/embed/kec3v?view=Editor+%2B+Preview&module=%2Fsrc%2Findex.tsx 該專案在 GitHub 上有 22k+ Stars,有 200k+ 開發人員使用。 https://github.com/recharts/recharts 明星 Recharts ⭐️ --- 8. [React Joyride](https://github.com/gilbarbara/react-joyride) - 在您的應用程式中建立導遊。 ------------------------------------------------------------------------------- ![反應兜風](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ph7rt2bxqbxi67r47on8.png) ![反應兜風](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ov4wzohwszgv5v06cin4.png) 導覽是向新用戶展示您的應用程式或解釋新功能的絕佳方式。它改善了用戶體驗並可以創造個人化的觸感。 開始使用以下 npm 指令。 ``` npm i react-joyride ``` 您可以這樣使用它。 ``` import React, { useState } from 'react'; import Joyride from 'react-joyride'; /* * If your steps are not dynamic you can use a simple array. * Otherwise you can set it as a state inside your component. */ const steps = [ { target: '.my-first-step', content: 'This is my awesome feature!', }, { target: '.my-other-step', content: 'This another awesome feature!', }, ]; export default function App() { // If you want to delay the tour initialization you can use the `run` prop return ( <div> <Joyride steps={steps} /> ... </div> ); } ``` 它們還提供[元件列表](https://docs.react-joyride.com/custom-components)以及自訂預設用戶介面的簡單方法。 您可以閱讀[文件](https://docs.react-joyride.com/)並查看[演示](https://react-joyride.com/)。 您也可以嘗試[codesandbox](https://codesandbox.io/p/devbox/github/gilbarbara/react-joyride-demo/tree/main/?embed=1)上的東西。 他們在 GitHub 上有超過 6k 顆星,npm 套件每週下載量超過 25 萬次。 https://github.com/gilbarbara/react-joyride Star React Joyride ⭐️ --- 9. [SVGR](https://github.com/gregberge/svgr) - 將 SVG 轉換為 React 元件。 ------------------------------------------------------------------ ![svgr](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/94hpre3yl3ttu5zdexsv.png) SVGR 是一個將 SVG 轉換為 React 元件的通用工具。 它需要一個原始的 SVG 並將其轉換為隨時可用的 React 元件。 開始使用以下 npm 指令。 ``` npm install @svgr/core ``` 例如,您採用這個 SVG。 ``` <?xml version="1.0" encoding="UTF-8"?> <svg width="48px" height="1px" viewBox="0 0 48 1" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" > <!-- Generator: Sketch 46.2 (44496) - http://www.bohemiancoding.com/sketch --> <title>Rectangle 5</title> <desc>Created with Sketch.</desc> <defs></defs> <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="19-Separator" transform="translate(-129.000000, -156.000000)" fill="#063855" > <g id="Controls/Settings" transform="translate(80.000000, 0.000000)"> <g id="Content" transform="translate(0.000000, 64.000000)"> <g id="Group" transform="translate(24.000000, 56.000000)"> <g id="Group-2"> <rect id="Rectangle-5" x="25" y="36" width="48" height="1"></rect> </g> </g> </g> </g> </g> </g> </svg> ``` 執行SVGR後,將轉換為. ``` import * as React from 'react' const SvgComponent = (props) => ( <svg width="1em" height="1em" viewBox="0 0 48 1" {...props}> <path d="M0 0h48v1H0z" fill="currentColor" fillRule="evenodd" /> </svg> ) export default SvgComponent ``` 它使用[SVGO](https://github.com/svg/svgo)優化 SVG,並使用 Prettier 格式化程式碼。 將 HTML 轉換為 JSX 需要幾個步驟: 1. 將 SVG 轉換為 HAST (HTML AST) 2. 將 HAST 轉換為 Babel AST (JSX AST) 3. 使用 Babel 轉換 AST(重新命名屬性、更改屬性值…) 您可以在[Playground](https://react-svgr.com/playground/)閱讀[文件](https://react-svgr.com/docs/getting-started)並檢查內容。 該專案在 GitHub 上擁有 10k+ Stars,有超過 800 萬開發者使用,npm 上每週下載量超過 800k。 https://github.com/gregberge/svgr 明星 SVGR ⭐️ --- 10. [React Sortable Tree](https://github.com/frontend-collective/react-sortable-tree) - 用於巢狀資料和層次結構的拖放可排序元件。 ------------------------------------------------------------------------------------------------------------ ![反應可排序樹](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/907c4rnmev2wx1abq0r7.png) 一個 React 元件,支援對分層資料進行拖放排序。 ![反應可排序樹](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z4tm32vuteqaw5m7crag.png) 開始使用以下 npm 指令。 ``` npm install react-sortable-tree --save ``` 您可以這樣使用它。 ``` import React, { Component } from 'react'; import SortableTree from 'react-sortable-tree'; import 'react-sortable-tree/style.css'; // This only needs to be imported once in your app export default class Tree extends Component { constructor(props) { super(props); this.state = { treeData: [ { title: 'Chicken', children: [{ title: 'Egg' }] }, { title: 'Fish', children: [{ title: 'fingerline' }] }, ], }; } render() { return ( <div style={{ height: 400 }}> <SortableTree treeData={this.state.treeData} onChange={treeData => this.setState({ treeData })} /> </div> ); } } ``` 檢查由此獲得的各種[道具選項](https://github.com/frontend-collective/react-sortable-tree?tab=readme-ov-file#props)和[主題](https://github.com/frontend-collective/react-sortable-tree?tab=readme-ov-file#featured-themes)。 您可以閱讀[文件](https://github.com/frontend-collective/react-sortable-tree?tab=readme-ov-file#getting-started)並查看[Storybook](https://frontend-collective.github.io/react-sortable-tree/?path=/story/basics--minimal-implementation) ,以獲取一些基本和高級功能的演示。 它可能不會被積極維護(仍然沒有存檔),因此您也可以使用[維護的 fork 版本](https://github.com/nosferatu500/react-sortable-tree)。 該專案在 GitHub 上擁有超過 4,500 個 Star,並被超過 5,000 名開發人員使用。 https://github.com/frontend-collective/react-sortable-tree Star React 可排序樹 ⭐️ --- 11. [React Hot Toast](https://github.com/timolins/react-hot-toast) - 冒煙的 Hot React 通知。 -------------------------------------------------------------------------------------- ![反應熱吐司](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lw4veo990lspkchhwz64.png) React Hot Toast 透過簡單的自訂選項提供了驚人的 🔥 預設體驗。它利用 Promise API 進行自動加載,確保平穩過渡。 它重量輕,不到 5kb,但仍然可以存取,同時為開發人員提供了像`useToaster()`這樣的無頭鉤子。 首先將 Toaster 加入到您的應用程式中。它將負責渲染發出的所有通知。現在您可以從任何地方觸發 toast() ! 開始使用以下 npm 指令。 ``` npm install react-hot-toast ``` 這就是它的易用性。 ``` import toast, { Toaster } from 'react-hot-toast'; const notify = () => toast('Here is your toast.'); const App = () => { return ( <div> <button onClick={notify}>Make me a toast</button> <Toaster /> </div> ); }; ``` ![主題選項](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tl8ezjabacdllw8qnd41.png) ![主題選項](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zksldf8goqbytcuumhac.png) 他們有很多自訂選項,但`useToaster()`掛鉤為您提供了一個無頭系統,可以為您管理通知狀態。這使得建立您的通知系統變得更加容易。 您可以閱讀[文件](https://react-hot-toast.com/docs)、[樣式指南](https://react-hot-toast.com/docs/styling)並查看[示範](https://react-hot-toast.com/)。 該專案在 GitHub 上有 8k+ Stars,有 230k+ 開發者使用。 https://github.com/timolins/react-hot-toast Star React Hot Toast ⭐️ --- 12. [Payload](https://github.com/payloadcms/payload) - 建立現代後端+管理 UI 的最佳方式。 -------------------------------------------------------------------------- ![有效負載](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xev60f07ilzqlfdwni0p.png) Payload 是一個無頭 CMS 和應用程式框架。它旨在促進您的開發過程,但重要的是,當您的應用程式變得更加複雜時,不要妨礙您。 Payload 沒有黑魔法,完全開源,它既是一個應用程式框架,也是一個無頭 CMS。它確實是適用於 TypeScript 的 Rails,並且您會獲得一個管理面板。您可以使用此[YouTube 影片](https://www.youtube.com/watch?v=In_lFhzmbME)了解有關 Payload 的更多資訊。 https://www.youtube.com/watch?v=In\_lFhzmbME 您可以透過使用Payload來了解[其中涉及的概念](https://payloadcms.com/docs/getting-started/concepts)。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nqn1uqupsdkexoq913mm.png) 有效負載透過您選擇的資料庫適配器與您的資料庫進行互動。目前,Payload 正式支援兩種資料庫適配器: 1. MongoDB 與 Mongoose 2. Postgres 帶毛毛雨 開始使用以下命令。 ``` npx create-payload-app@latest ``` 您必須產生 Payload 金鑰並更新`server.ts`以初始化 Payload。 ``` import express from 'express' import payload from 'payload' require('dotenv').config() const app = express() const start = async () => { await payload.init({ secret: process.env.PAYLOAD_SECRET, express: app, }) app.listen(3000, async () => { console.log( "Express is now listening for incoming connections on port 3000." ) }) } start() ``` ![使用 nextjs 進行有效負載](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ghnnf34k70hpb0zjsf5f.png) 您可以閱讀[文件](https://payloadcms.com/docs/getting-started/what-is-payload)並查看[演示](https://demo.payloadcms.com/?_gl=1*9x0za3*_ga*NzEzMzkwNzIuMTcxMDE2NDk1MA..*_ga_FLQ5THRMZQ*MTcxMDE2NDk1MC4xLjEuMTcxMDE2NDk1MS4wLjAuMA..)。 他們還提供與 Payload + Stripe 無縫整合的[電子商務模板](https://github.com/payloadcms/payload/tree/main/templates/ecommerce)。此範本具有令人驚嘆的、功能齊全的前端,包括購物車、結帳流程、訂單管理等元件。 Payload 在 GitHub 上擁有 18k+ Stars,並且有超過 290 個版本,因此它們不斷改進,尤其是在資料庫支援方面。 https://github.com/payloadcms/payload 明星有效負載 ⭐️ --- 13. [React Player](https://github.com/cookpete/react-player) - 用於播放各種 URL 的 React 元件。 ------------------------------------------------------------------------------------- ![反應玩家](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/immw7vlgrdfbfxgts0a0.png) 用於播放各種 URL 的 React 元件,包括檔案路徑、YouTube、Facebook、Twitch、SoundCloud、Streamable、Vimeo、Wistia、Mixcloud、DailyMotion 和 Kaltura。您可以看到[支援的媒體](https://github.com/cookpete/react-player?tab=readme-ov-file#supported-media)清單。 ReactPlayer 的維護工作由 Mux 接管,這使它們成為一個不錯的選擇。 開始使用以下 npm 指令。 ``` npm install react-player ``` 您可以這樣使用它。 ``` import React from 'react' import ReactPlayer from 'react-player' // Render a YouTube video player <ReactPlayer url='https://www.youtube.com/watch?v=LXb3EKWsInQ' /> // If you only ever use one type, use imports such as react-player/youtube to reduce your bundle size. // like this: import ReactPlayer from 'react-player/youtube' ``` 您也可以使用`react-player/lazy`為您傳入的URL 延遲載入適當的播放器。這會為您的輸出加入幾個reactPlayer 區塊,但會減少主包的大小。 ``` import React from 'react' import ReactPlayer from 'react-player/lazy' // Lazy load the YouTube player <ReactPlayer url='https://www.youtube.com/watch?v=ysz5S6PUM-U' /> ``` 您可以閱讀[文件](https://github.com/cookpete/react-player?tab=readme-ov-file#props)並查看[演示](https://cookpete.github.io/react-player/)。他們提供了大量的選項,包括加入字幕並以簡單的方式使其響應。 它們在 GitHub 上擁有超過 8000 顆星,被超過 135,000 名開發人員使用,並且 npm 軟體包[每週的下載量超過 800k](https://www.npmjs.com/package/react-player) 。 https://github.com/cookpete/react-player 明星 React 播放器 ⭐️ --- 14. [Victory](https://github.com/FormidableLabs/victory) - 用於建立互動式資料視覺化的 React 元件。 ---------------------------------------------------------------------------------- ![勝利](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dbayfgbrutvffkk2slja.png) Victory 是一個可組合 React 元件的生態系統,用於建立互動式資料視覺化。 ![元件類型](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ua3jegboex4n21aid20.png) 開始使用以下 npm 指令。 ``` npm i --save victory ``` 您可以這樣使用它。 ``` <VictoryChart domainPadding={{ x: 20 }} > <VictoryHistogram style={{ data: { fill: "#c43a31" } }} data={sampleHistogramDateData} bins={[ new Date(2020, 1, 1), new Date(2020, 4, 1), new Date(2020, 8, 1), new Date(2020, 11, 1) ]} /> </VictoryChart> ``` 這就是它的渲染方式。他們還提供通常有用的動畫和主題選項。 ![勝利圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wdxztxui9zjtue0fz1jo.png) 您可以閱讀[文件](https://commerce.nearform.com/open-source/victory/docs)並按照[教學](https://commerce.nearform.com/open-source/victory/docs/native)開始。他們提供大約 15 種不同的圖表選項。 它也可用於[React Native(文件)](https://commerce.nearform.com/open-source/victory/docs/native) ,所以這是一個優點。我還建議您查看他們的常見[問題解答](https://commerce.nearform.com/open-source/victory/docs/faq#frequently-asked-questions-faq),其中描述了常見問題的程式碼解決方案和解釋,例如樣式、註釋(標籤)、處理軸。 該專案在 GitHub 上擁有 10k+ Stars,並在 GitHub 上有 23k+ 開發人員使用。 https://github.com/FormidableLabs/victory 勝利之星 ⭐️ --- 15. [React Slick](https://github.com/akiran/react-slick) - React 輪播元件。 ---------------------------------------------------------------------- ![反應圓滑](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4fn2aafcxs281yliyyv0.png) React Slick 是一個使用 React 建構的輪播元件。它是一個光滑的旋轉木馬的反應端口 開始使用以下 npm 指令。 ``` npm install react-slick --save ``` 這是使用自訂分頁的方法。 ``` import React, { Component } from "react"; import Slider from "react-slick"; import { baseUrl } from "./config"; function CustomPaging() { const settings = { customPaging: function(i) { return ( <a> <img src={`${baseUrl}/abstract0${i + 1}.jpg`} /> </a> ); }, dots: true, dotsClass: "slick-dots slick-thumb", infinite: true, speed: 500, slidesToShow: 1, slidesToScroll: 1 }; return ( <div className="slider-container"> <Slider {...settings}> <div> <img src={baseUrl + "/abstract01.jpg"} /> </div> <div> <img src={baseUrl + "/abstract02.jpg"} /> </div> <div> <img src={baseUrl + "/abstract03.jpg"} /> </div> <div> <img src={baseUrl + "/abstract04.jpg"} /> </div> </Slider> </div> ); } export default CustomPaging; ``` ![自訂分頁](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hh3qtgnftoapsrdx8w4y.png) 您可以閱讀有關可用的[prop 選項](https://react-slick.neostack.com/docs/api)和[方法](https://react-slick.neostack.com/docs/api#methods)的資訊。 您可以閱讀[文件](https://react-slick.neostack.com/docs/get-started)和所有帶有程式碼和輸出[的範例集](https://react-slick.neostack.com/docs/example/)。 他們在 GitHub 上有超過 11k 顆星,並且有超過 36 萬開發者在 GitHub 上使用它。 https://github.com/akiran/react-slick Star React Slick ⭐️ --- 16. [Medusa](https://github.com/medusajs/medusa) - 數位商務的建構模組。 ------------------------------------------------------------- ![美杜莎](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h7vd1qsx7l1jdsz2cnq0.png) Medusa 是一組商務模組和工具,可讓您建立豐富、可靠且高效能的商務應用程式,而無需重新發明核心商務邏輯。 這些模組可以客製化並用於建立高級電子商務商店、市場或任何需要基礎商務原語的產品。所有模組都是開源的,可以在 npm 上免費取得。 開始使用以下 npm 指令。 ``` npm install medusa-react @tanstack/[email protected] @medusajs/medusa ``` 將其包含在`app.ts`中。 只有 MedusaProvider 的子級才能從其鉤子中受益。因此,Storefront 元件及其子元件現在可以使用 Medusa React 公開的鉤子。 ``` import { MedusaProvider } from "medusa-react" import Storefront from "./Storefront" import { QueryClient } from "@tanstack/react-query" import React from "react" const queryClient = new QueryClient() const App = () => { return ( <MedusaProvider queryClientProviderProps={{ client: queryClient }} baseUrl="http://localhost:9000" > <Storefront /> </MedusaProvider> ) } export default App ``` 例如,這就是您如何使用突變來建立購物車。 ``` import { useCreateCart } from "medusa-react" const Cart = () => { const createCart = useCreateCart() const handleClick = () => { createCart.mutate({}) // create an empty cart } return ( <div> {createCart.isLoading && <div>Loading...</div>} {!createCart.data?.cart && ( <button onClick={handleClick}> Create cart </button> )} {createCart.data?.cart?.id && ( <div>Cart ID: {createCart.data?.cart.id}</div> )} </div> ) } export default Cart ``` 他們提供了一套電子商務模組(大量選項),例如折扣、價目表、禮品卡等。 ![電子商務模組](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x00lbkpny66esa1yep4u.png) 它們還提供了一種簡單的管理員和客戶身份驗證方法,您可以在[文件](https://docs.medusajs.com/)中閱讀。 他們提供了[nextjs 入門模板](https://docs.medusajs.com/starters/nextjs-medusa-starter)和[Medusa React](https://docs.medusajs.com/medusa-react/overview)作為 SDK。 該專案在 GitHub 上有 22k+ Stars,有 4k+ 開發者使用。 https://github.com/medusajs/medusa 明星美杜莎 ⭐️ --- 17. [React Markdown](https://github.com/remarkjs/react-markdown) - React 的 Markdown 元件. --------------------------------------------------------------------------------------- ![反應降價](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hcl4bq3m0r415mknvv5h.png) Markdown 至關重要,使用 React 渲染它對於各種場景都非常有用。 它提供了一個 React 元件,能夠安全地將一串 Markdown 渲染到 React 元素中。您可以透過傳遞外掛程式並指定要使用的元件而不是標準 HTML 元素來自訂 Markdown 的轉換。 開始使用以下 npm 指令。 ``` npm i react-markdown ``` 您可以這樣使用它。 ``` import React from 'react' import {createRoot} from 'react-dom/client' import Markdown from 'react-markdown' import remarkGfm from 'remark-gfm' const markdown = `Just a link: www.nasa.gov.` createRoot(document.body).render( <Markdown remarkPlugins={[remarkGfm]}>{markdown}</Markdown> ) ``` 等效的 JSX 是。 ``` <p> Just a link: <a href="http://www.nasa.gov">www.nasa.gov</a>. </p> ``` 他們還提供了一份[備忘錄](https://commonmark.org/help/)和一個十分鐘的逐步[教學](https://commonmark.org/help/tutorial/)。 ![教學](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2oboj1ooemoo2j9uh2d7.png) 您可以閱讀[文件](https://github.com/remarkjs/react-markdown?tab=readme-ov-file#install)並查看[演示](https://remarkjs.github.io/react-markdown/)。 該專案在 GitHub 上有 12k+ Stars,[每週下載量超過 2700k](https://www.npmjs.com/package/react-markdown) ,並被 200k+ 開發人員使用,證明了它的真正有用性。 https://github.com/remarkjs/react-markdown Star React Markdown ⭐️ --- 18. [React JSONSchema Form](https://github.com/rjsf-team/react-jsonschema-form) - 用於從 JSON Schema 建立 Web 表單。 ------------------------------------------------------------------------------------------------------------ ![反應 jsonform 模式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/36bma59hylme02fg5mmi.png) `react-jsonschema-form`會自動從 JSON Schema 產生 React 表單,使其非常適合僅使用 JSON schema 為任何資料產生表單。它提供了像 uiSchema 這樣的自訂選項來自訂預設主題之外的表單外觀。 開始使用以下 npm 指令。 ``` npm install @rjsf/core @rjsf/utils @rjsf/validator-ajv8 --save ``` 您可以這樣使用它。 ``` import { RJSFSchema } from '@rjsf/utils'; import validator from '@rjsf/validator-ajv8'; const schema: RJSFSchema = { title: 'Todo', type: 'object', required: ['title'], properties: { title: { type: 'string', title: 'Title', default: 'A new task' }, done: { type: 'boolean', title: 'Done?', default: false }, }, }; const log = (type) => console.log.bind(console, type); render( <Form schema={schema} validator={validator} onChange={log('changed')} onSubmit={log('submitted')} onError={log('errors')} />, document.getElementById('app') ); ``` 他們提供[高級定制](https://rjsf-team.github.io/react-jsonschema-form/docs/advanced-customization/)選項,包括定制小部件。 您可以閱讀[文件](https://rjsf-team.github.io/react-jsonschema-form/docs/)並查看[即時遊樂場](https://rjsf-team.github.io/react-jsonschema-form/)。 它在 GitHub 上擁有超過 13k 個 Star,並被 5k+ 開發人員使用。他們在`v5`上發布了 190 多個版本,因此他們正在不斷改進。 https://github.com/rjsf-team/react-jsonschema-form Star React JSONSchema 表單 ⭐️ --- 19. [Craft.js](https://github.com/prevwong/craft.js) - 建立可擴充的拖放頁面編輯器。 --------------------------------------------------------------------- ![craft.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ydxmz82mswa2tlk5onbs.png) 頁面編輯器可以增強使用者體驗,但從頭開始建立頁面編輯器可能會令人望而生畏。現有庫提供具有可編輯元件的預先建置編輯器,但自訂通常需要修改庫本身。 Craft.js 透過模組化頁面編輯器元件、透過拖放功能簡化自訂以及渲染管理來解決這個問題。在 React 中設計你的編輯器,無需複雜的插件系統,專注於你的特定需求和規格。 開始使用以下 npm 指令。 ``` npm install --save @craftjs/core ``` 他們還提供了有關如何入門的[簡短教程](https://craft.js.org/docs/guides/basic-tutorial)。我不會介紹它,因為它非常簡單且詳細。 您可以閱讀[文件](https://craft.js.org/docs/overview)並查看[即時演示](https://craft.js.org/)以及另一個[即時範例](https://craft.js.org/examples/basic)。 它在 GitHub 上有大約 6k+ Stars,但考慮到它們正在改進,仍然很有用。 https://github.com/prevwong/craft.js Star Craft.js ⭐️ --- 20. [Gatsby](https://github.com/gatsbyjs/gatsby) - 最好的基於 React 的框架,具有內建的效能、可擴展性和安全性。 ------------------------------------------------------------------------------------ ![蓋茲比](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ybxi9gplvm2kr8abbtzy.png) Gatsby 是一個基於 React 的框架,使開發人員能夠建立閃電般快速的網站和應用程式,將動態渲染的靈活性與靜態網站生成的速度融為一體。 憑藉可自訂的 UI 和對各種資料來源的支援等功能,Gatsby 提供了無與倫比的控制和可擴展性。此外,它還可以自動進行效能最佳化,使其成為靜態網站的首選。 開始使用以下 npm 指令。 ``` npm init gatsby ``` 這就是如何在 Gatsby(反應元件)中使用`Link` 。 ``` import React from "react" import { Link } from "gatsby" const Page = () => ( <div> <p> Check out my <Link to="/blog">blog</Link>! </p> <p> {/* Note that external links still use `a` tags. */} Follow me on <a href="https://twitter.com/gatsbyjs">Twitter</a>! </p> </div> ) ``` 他們提供了一組[入門模板,](https://www.gatsbyjs.com/starters/)其中包含如何使用它、涉及的依賴項以及每個模板的演示。 ![範本](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8l35rwb1is60d5q506qu.png) 您可以閱讀有關 Gatsby 的一些[常見概念,](https://www.gatsbyjs.com/docs/conceptual/gatsby-concepts/)例如 React Hydration、Gatsby 建置流程等。 您可以閱讀[文件](https://www.gatsbyjs.com/docs/)並查看入門[教學課程](https://www.gatsbyjs.com/docs/tutorial/)。 Gatsby 在 GitHub 上擁有超過 55,000 顆星,並被超過 240,000 名開發者使用 https://github.com/gatsbyjs/gatsby 明星蓋茲比 ⭐️ --- 21. [Chat UI Kit React](https://github.com/chatscope/chat-ui-kit-react) - 在幾分鐘內使用 React 建立您的聊天 UI。 -------------------------------------------------------------------------------------------------- ![chatscope 聊天 ui 套件反應](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0ynb25x1se0riwbvq5uv.png) Chatscope 的聊天 UI 工具包是一個用於開發網頁聊天應用程式的開源 UI 工具包。 儘管該專案並未廣泛使用,但這些功能對於剛剛查看該專案的初學者來說還是很有用的。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m1y87b1clbi00tojxgzi.png) 開始使用以下 npm 指令。 ``` npm install @chatscope/chat-ui-kit-react ``` 這就是建立 GUI 的方法。 ``` import styles from '@chatscope/chat-ui-kit-styles/dist/default/styles.min.css'; import { MainContainer, ChatContainer, MessageList, Message, MessageInput } from '@chatscope/chat-ui-kit-react'; <div style={{ position:"relative", height: "500px" }}> <MainContainer> <ChatContainer> <MessageList> <Message model={{ message: "Hello my friend", sentTime: "just now", sender: "Joe" }} /> </MessageList> <MessageInput placeholder="Type message here" /> </ChatContainer> </MainContainer> </div> ``` 您可以閱讀[文件](https://chatscope.io/docs/)。 故事書中有更[詳細的文件](https://chatscope.io/storybook/react/?path=/docs/documentation-introduction--docs)。 它提供了一些方便的元件,例如[`TypingIndicator`](https://chatscope.io/storybook/react/?path=/docs/components-typingindicator--docs) 、 [`Multiline Incoming`](https://chatscope.io/storybook/react/?path=/story/components-message--multiline-incoming)等等。 我知道你們中的一些人更喜歡透過部落格來了解整個結構,因此你可以閱讀使用 Chat UI Kit React 的 Rollbar 的[如何將 ChatGPT 與 React 整合](https://rollbar.com/blog/how-to-integrate-chatgpt-with-react/)。 您可以看到的一些演示: - [聊天機器人使用者介面](https://mars.chatscope.io/) - [與朋友聊天](https://chatscope.io/demo/chat-friends/)- 看看這個! ![聊天朋友演示快照](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hyhqti9yl02rludkocy.png) https://github.com/chatscope/chat-ui-kit-react Star Chat UI Kit React ⭐️ --- 22. [Botonic](https://github.com/hubtype/botonic) - 用於建立會話應用程式的 React 框架。 ------------------------------------------------------------------------- ![植物性的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yxeslrg9cjbkej0hcth4.png) Botonic 是一個全端 Javascript 框架,用於建立在多個平台上執行的聊天機器人和現代對話應用程式:Web、行動和訊息應用程式(Messenger、WhatsApp、Telegram 等)。它建構在 ⚛️ React、Serverless 和 Tensorflow.js 之上。 如果您不了解對話應用程式的概念,可以在[官方部落格](https://www.hubtype.com/blog/what-are-conversational-apps)上閱讀它們。 使用 Botonic,您可以建立包含最佳文字外介面(簡單性、自然語言互動)和圖形介面(多媒體、視覺上下文、豐富互動)的會話應用程式。 這是一個強大的組合,可以提供比僅依賴文字和 NLP 的傳統聊天機器人更好的用戶體驗。 這就是 Botonic 的簡單方式。 ``` export default class extends React.Component { static async botonicInit({ input, session, params, lastRoutePath }) { await humanHandOff(session)) } render() { return ( <Text> Thanks for contacting us! One of our agents will attend you as soon as possible. </Text> ) } } ``` 它們也支援 TypeScript,所以這是一個優點。 您可以看到一些使用 Botonic 建置的[範例](https://botonic.io/examples/)及其原始程式碼。 您可以閱讀[文件](https://botonic.io/docs/welcome)以及如何[從頭開始建立會話應用程式](https://botonic.io/docs/create-convapp)。 https://github.com/hubtype/botonic Star Botonic ⭐️ --- 23. [React Flowbite](https://github.com/themesberg/flowbite-react) - 為 Flowbite 和 Tailwind CSS 建構的 React 元件. ------------------------------------------------------------------------------------------------------------ ![反應流咬](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8vt1coti9k3ppmv0y28u.png) 每個人對他們想要用來建立網站的使用者介面都有不同的偏好。 Flowbite React 是 UI 元件的開源集合,在 React 中建置,具有來自 Tailwind CSS 的實用程式類,您可以將其用作使用者介面和網站的起點。 開始使用以下 npm 指令。 ``` npm i flowbite-react ``` 這是一起使用表格和鍵盤元件的方法。 ``` 'use client'; import { Kbd, Table } from 'flowbite-react'; import { MdKeyboardArrowDown, MdKeyboardArrowLeft, MdKeyboardArrowRight, MdKeyboardArrowUp } from 'react-icons/md'; function Component() { return ( <Table> <Table.Head> <Table.HeadCell>Key</Table.HeadCell> <Table.HeadCell>Description</Table.HeadCell> </Table.Head> <Table.Body className="divide-y"> <Table.Row className="bg-white dark:border-gray-700 dark:bg-gray-800"> <Table.Cell className="whitespace-nowrap font-medium text-gray-900 dark:text-white"> <Kbd>Shift</Kbd> <span>or</span> <Kbd>Tab</Kbd> </Table.Cell> <Table.Cell>Navigate to interactive elements</Table.Cell> </Table.Row> <Table.Row className="bg-white dark:border-gray-700 dark:bg-gray-800"> <Table.Cell className="whitespace-nowrap font-medium text-gray-900 dark:text-white"> <Kbd>Enter</Kbd> or <Kbd>Spacebar</Kbd> </Table.Cell> <Table.Cell>Ensure elements with ARIA role="button" can be activated with both key commands.</Table.Cell> </Table.Row> <Table.Row className="bg-white dark:border-gray-700 dark:bg-gray-800"> <Table.Cell className="whitespace-nowrap font-medium text-gray-900 dark:text-white"> <span className="inline-flex gap-1"> <Kbd icon={MdKeyboardArrowUp} /> <Kbd icon={MdKeyboardArrowDown} /> </span> <span> or </span> <span className="inline-flex gap-1"> <Kbd icon={MdKeyboardArrowLeft} /> <Kbd icon={MdKeyboardArrowRight} /> </span> </Table.Cell> <Table.Cell>Choose and activate previous/next tab.</Table.Cell> </Table.Row> </Table.Body> </Table> ); } ``` ![kbd 和表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mnu5xqlqob72t9oxkb4k.png) 您可以閱讀[文件](https://www.flowbite-react.com/docs/getting-started/introduction)並查看[Storybook](https://storybook.flowbite-react.com/?path=/story/components-accordion--always-open)中的功能。您也可以查看[元件](https://www.flowbite-react.com/docs/components/accordion)清單。 在我看來,如果您想快速設定 UI,但又不想最終為高品質的開源專案使用預先定義的庫元件,那麼這很好。 該專案在 GitHub 上擁有超過 1,500 顆星,擁有超過 37,000 名開發者的用戶群,並受到社群的廣泛認可和信任,使其成為一個可靠的選擇。 https://github.com/themesberg/flowbite-react Star React Flowbite ⭐️ --- 24. [DND 套件](https://github.com/clauderic/dnd-kit)- 輕量級、高效能、可存取且可擴展的拖放功能。 ------------------------------------------------------------------------- ![免打擾套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oz5m8hf4t4u4v2jzusl1.png) 這是一個強大的 React 拖放工具包,擁有可自訂的碰撞檢測、多個啟動器和自動滾動等功能。 它的設計考慮到了 React,提供了方便集成的鉤子,無需進行重大的架構更改。支援從清單到網格和虛擬化清單的各種用例,它既是動態的又是輕量級的,沒有外部相依性。 開始使用以下 npm 指令。 ``` npm install @dnd-kit/core ``` 這就是建立可拖放元件的方法。 `Example.jsx` ``` import React, {useState} from 'react'; import {DndContext} from '@dnd-kit/core'; import {Draggable} from './Draggable'; import {Droppable} from './Droppable'; function Example() { const [parent, setParent] = useState(null); const draggable = ( <Draggable id="draggable"> Go ahead, drag me. </Draggable> ); return ( <DndContext onDragEnd={handleDragEnd}> {!parent ? draggable : null} <Droppable id="droppable"> {parent === "droppable" ? draggable : 'Drop here'} </Droppable> </DndContext> ); function handleDragEnd({over}) { setParent(over ? over.id : null); } } ``` `Droppable.jsx` ``` import React from 'react'; import {useDroppable} from '@dnd-kit/core'; export function Droppable(props) { const {isOver, setNodeRef} = useDroppable({ id: props.id, }); const style = { opacity: isOver ? 1 : 0.5, }; return ( <div ref={setNodeRef} style={style}> {props.children} </div> ); } ``` `Draggable.jsx` ``` import React from 'react'; import {useDraggable} from '@dnd-kit/core'; import {CSS} from '@dnd-kit/utilities'; function Draggable(props) { const {attributes, listeners, setNodeRef, transform} = useDraggable({ id: props.id, }); const style = { // Outputs `translate3d(x, y, 0)` transform: CSS.Translate.toString(transform), }; return ( <button ref={setNodeRef} style={style} {...listeners} {...attributes}> {props.children} </button> ); } ``` 我將可拖曳元件放在可放置元件上。 ![自訂元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cf98be5hq9am3f2s1dwv.png) 您可以閱讀[文件](https://docs.dndkit.com/)以及滑鼠和指標等[感測器的選項](https://docs.dndkit.com/introduction/installation#core-library)。 它在 GitHub 上擁有 10k+ Stars,並被 GitHub 上 47k+ 開發人員使用。 https://github.com/clauderic/dnd-kit 明星免打擾套件 ⭐️

使用 React 開發時應該了解的 17 個函式庫

長話短說 ==== 我收集了您應該了解的 React 庫,以建立許多不同類型的專案並成為 React 奇才🧙‍♂️。 其中每一項都是獨一無二的,並且都有自己的用例。 別忘了給他們加星號🌟 讓我們開始吧! ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/16rwdtymlmp6y17ocz59.gif) --- 1. [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 建立應用內人工智慧聊天機器人、代理程式和文字區域 ------------------------------------------------------------------------------------ ![副駕駛套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzuxjfog2ldam3csrl62.png) 將 AI 功能整合到 React 中是很困難的,這就是 Copilot 的用武之地。一個簡單快速的解決方案,可將可投入生產的 Copilot 整合到任何產品中! 您可以使用兩個 React 元件將關鍵 AI 功能整合到 React 應用程式中。它們還提供內建(完全可自訂)Copilot 原生 UX 元件,例如`<CopilotKit />` 、 `<CopilotPopup />` 、 `<CopilotSidebar />` 、 `<CopilotTextarea />` 。 開始使用以下 npm 指令。 ``` npm i @copilotkit/react-core @copilotkit/react-ui ``` Copilot Portal 是 CopilotKit 提供的元件之一,CopilotKit 是一個應用程式內人工智慧聊天機器人,可查看目前應用狀態並在應用程式內採取操作。它透過插件與應用程式前端和後端以及第三方服務進行通訊。 這就是整合聊天機器人的方法。 `CopilotKit`必須包裝與 CopilotKit 互動的所有元件。建議您也開始使用`CopilotSidebar` (您可以稍後切換到不同的 UI 提供者)。 ``` "use client"; import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import "@copilotkit/react-ui/styles.css"; export default function RootLayout({children}) { return ( <CopilotKit url="/path_to_copilotkit_endpoint/see_below"> <CopilotSidebar> {children} </CopilotSidebar> </CopilotKit> ); } ``` 您可以使用此[快速入門指南](https://docs.copilotkit.ai/getting-started/quickstart-backend)設定 Copilot 後端端點。 之後,您可以讓 Copilot 採取行動。您可以閱讀如何提供[外部上下文](https://docs.copilotkit.ai/getting-started/quickstart-chatbot#provide-context)。您可以使用`useMakeCopilotReadable`和`useMakeCopilotDocumentReadable`反應掛鉤來執行此操作。 ``` "use client"; import { useMakeCopilotActionable } from '@copilotkit/react-core'; // Let the copilot take action on behalf of the user. useMakeCopilotActionable( { name: "setEmployeesAsSelected", // no spaces allowed in the function name description: "Set the given employees as 'selected'", argumentAnnotations: [ { name: "employeeIds", type: "array", items: { type: "string" } description: "The IDs of employees to set as selected", required: true } ], implementation: async (employeeIds) => setEmployeesAsSelected(employeeIds), }, [] ); ``` 您可以閱讀[文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea)並查看[演示影片](https://github.com/CopilotKit/CopilotKit?tab=readme-ov-file#demo)。 您可以輕鬆整合 Vercel AI SDK、OpenAI API、Langchain 和其他 LLM 供應商。您可以按照本[指南](https://docs.copilotkit.ai/getting-started/quickstart-chatbot)將聊天機器人整合到您的應用程式中。 基本概念是在幾分鐘內建立可用於基於 LLM 的應用程式的 AI 聊天機器人。 用例是巨大的,作為開發人員,我們絕對應該在下一個專案中嘗試使用 CopilotKit。 https://github.com/CopilotKit/CopilotKit Star CopilotKit ⭐️ --- 2. [xyflow](https://github.com/xyflow/xyflow) - 使用 React 建立基於節點的 UI。 -------------------------------------------------------------------- ![XY流](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yevpzvqpt3u6ahkqdrsl.png) XYFlow 是一個功能強大的開源程式庫,用於使用 React 或 Svelte 建立基於節點的 UI。它是一個 monorepo,提供[React Flow](https://reactflow.dev)和[Svelte Flow](https://svelteflow.dev) 。讓我們更多地了解可以使用 React flow 做什麼。 ![反應流](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8mzezlna4v4bx75z3omr.png) 您可以觀看此影片,在 60 秒內了解 React Flow。 https://www.youtube.com/watch?v=aUBWE41a900 有些功能在專業模式下可用,但免費層中的功能足以形成一個非常互動的流程。 React 流程以 TypeScript 編寫並使用 Cypress 進行測試。 開始使用以下 npm 指令。 ``` npm install reactflow ``` 以下介紹如何建立兩個節點( `Hello`和`World` ,並透過邊連接。節點具有預先定義的初始位置以防止重疊,並且我們還應用樣式來確保有足夠的空間來渲染圖形。 ``` import ReactFlow, { Controls, Background } from 'reactflow'; import 'reactflow/dist/style.css'; const edges = [{ id: '1-2', source: '1', target: '2' }]; const nodes = [ { id: '1', data: { label: 'Hello' }, position: { x: 0, y: 0 }, type: 'input', }, { id: '2', data: { label: 'World' }, position: { x: 100, y: 100 }, }, ]; function Flow() { return ( <div style={{ height: '100%' }}> <ReactFlow nodes={nodes} edges={edges}> <Background /> <Controls /> </ReactFlow> </div> ); } export default Flow; ``` 這就是它的樣子。您還可以新增標籤、更改類型並使其具有互動性。 ![你好世界](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xzerdd3ng0vtnz5rbgau.png) 您可以在 React Flow 的 API 參考中查看[完整的選項清單](https://reactflow.dev/api-reference/react-flow)以及元件、鉤子和實用程式。 最好的部分是您還可以加入[自訂節點](https://reactflow.dev/learn/customization/custom-nodes)。在您的自訂節點中,您可以渲染您想要的一切。您可以定義多個來源和目標句柄並呈現表單輸入或圖表。您可以查看此[codesandbox](https://codesandbox.io/p/sandbox/pensive-field-z4kv3w?file=%2FApp.js&utm_medium=sandpack)作為範例。 您可以閱讀[文件](https://reactflow.dev/learn)並查看 Create React App、Next.js 和 Remix 的[範例 React Flow 應用程式](https://github.com/xyflow/react-flow-example-apps)。 React Flow 附帶了幾個額外的[插件](https://reactflow.dev/learn/concepts/plugin-components)元件,可以幫助您使用 Background、Minimap、Controls、Panel、NodeToolbar 和 NodeResizer 元件製作更高級的應用程式。 例如,您可能已經注意到許多網站的背景中有圓點,增強了美觀性。要實現此模式,您可以簡單地使用 React Flow 中的後台元件。 ``` import { Background } from 'reactflow'; <Background color="#ccc" variant={'dots'} /> // this will be under React Flow component. Just an example. ``` ![背景元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/en2tl17ef31nydaycw18.png) 如果您正在尋找一篇快速文章,我建議您查看 Webkid 的[React Flow - A Library for Rendering Interactive Graphs](https://webkid.io/blog/react-flow-node-based-graph-library/) 。 React Flow 由 Webkid 開發和維護。 它在 GitHub 上有超過 19k 顆星,並且在`v11.10.4`上顯示它們正在不斷改進,npm 套件每週下載量超過 40 萬次。您可以輕鬆使用的最佳專案之一。 ![統計資料](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o99csz9epqmai3ixt859.png) https://github.com/xyflow/xyflow 星 xyflow ⭐️ --- 3. [Zod](https://github.com/colinhacks/zod) + [React Hook Form](https://github.com/react-hook-form) - 致命的驗證組合。 -------------------------------------------------------------------------------------------------------------- ![佐德](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1s6zvmqr0lv93vsrhofs.png) 第一個問題是:為什麼我在同一個選項中包含 Zod 和 React Hook 表單?好吧,請閱讀它來找出答案。 Zod 的目標是透過最大限度地減少重複的類型聲明來對開發人員友好。使用 Zod,您聲明一次驗證器,Zod 將自動推斷靜態 TypeScript 類型。將更簡單的類型組合成複雜的資料結構很容易。 開始使用以下 npm 指令。 ``` npm install zod ``` 這是您在建立字串架構時自訂一些常見錯誤訊息的方法。 ``` const name = z.string({ required_error: "Name is required", invalid_type_error: "Name must be a string", }); ``` ``` // It does provide lots of options // validations z.string().min(5, { message: "Must be 5 or more characters long" }); z.string().max(5, { message: "Must be 5 or fewer characters long" }); z.string().length(5, { message: "Must be exactly 5 characters long" }); z.string().email({ message: "Invalid email address" }); z.string().url({ message: "Invalid url" }); z.string().emoji({ message: "Contains non-emoji characters" }); z.string().uuid({ message: "Invalid UUID" }); z.string().includes("tuna", { message: "Must include tuna" }); z.string().startsWith("https://", { message: "Must provide secure URL" }); z.string().endsWith(".com", { message: "Only .com domains allowed" }); z.string().datetime({ message: "Invalid datetime string! Must be UTC." }); z.string().ip({ message: "Invalid IP address" }); ``` 請閱讀[文件](https://zod.dev/)以了解有關 Zod 的更多資訊。 它適用於 Node.js 和所有現代瀏覽器。 現在,第二部分來了。 有很多可用的表單整合。 ![形式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zz290xe2bpdsjvj6pzao.png) 雖然 Zod 可以驗證物件,但如果沒有自訂邏輯,它不會影響您的用戶端和後端。 React-hook-form 是用於客戶端驗證的優秀專案。例如,它可以顯示輸入錯誤。 ![反應鉤子形式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vy3m7inekd685t4nt59m.png) 開始使用以下 npm 指令。 ``` npm install react-hook-form ``` 這就是如何使用`React Hook Form` 。 ``` import { useForm, SubmitHandler } from "react-hook-form" type Inputs = { example: string exampleRequired: string } export default function App() { const { register, handleSubmit, watch, formState: { errors }, } = useForm<Inputs>() const onSubmit: SubmitHandler<Inputs> = (data) => console.log(data) console.log(watch("example")) // watch input value by passing the name of it return ( /* "handleSubmit" will validate your inputs before invoking "onSubmit" */ <form onSubmit={handleSubmit(onSubmit)}> {/* register your input into the hook by invoking the "register" function */} <input defaultValue="test" {...register("example")} /> {/* include validation with required or other standard HTML validation rules */} <input {...register("exampleRequired", { required: true })} /> {/* errors will return when field validation fails */} {errors.exampleRequired && <span>This field is required</span>} <input type="submit" /> </form> ) } ``` 您甚至可以隔離重新渲染,從而提高整體效能。 您可以閱讀[文件](https://react-hook-form.com/get-started)。 兩者結合起來就是一個很好的組合。嘗試一下! 我透過 Shadcn 發現了它,它使用它作為表單元件的預設值。我自己在幾個專案中使用過它,效果非常好。它提供了很大的靈活性,這確實很有幫助。 https://github.com/colinhacks/zod Star Zod ⭐️ https://github.com/react-hook-form Star React Hook Form ⭐️ --- 4. [React DND](https://github.com/react-dnd/react-dnd) - 用於 React 的拖放。 ---------------------------------------------------------------------- ![反應 dnd](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t0ywjp9hk8l4ocq145yr.png) 我還沒有完全實現拖放功能,而且我經常發現自己對選擇哪個選項感到困惑。我遇到的另一個選擇是[interactjs.io](https://interactjs.io/) ,根據我讀過的文件,它似乎非常有用。由於他們提供了詳細的範例,這非常容易。 ![拖放](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x2h85gcto3r3kwuj0nix.png) 但我現在只介紹 React DND。 開始使用以下 npm 指令。 ``` npm install react-dnd react-dnd-html5-backend ``` 除非您正在編寫自訂後端,否則您可能想要使用 React DnD 隨附的 HTML5 後端。 這是安裝`react-dnd-html5-backend`方法。閱讀[文件](https://react-dnd.github.io/react-dnd/docs/backends/html5)。 這是起點。 ``` import { HTML5Backend } from 'react-dnd-html5-backend' import { DndProvider } from 'react-dnd' export default class YourApp { render() { return ( <DndProvider backend={HTML5Backend}> /* Your Drag-and-Drop Application */ </DndProvider> ) } } ``` 透過這種方式,您可以非常輕鬆地實現卡片的拖放操作。 ``` // Let's make <Card text='Write the docs' /> draggable! import React from 'react' import { useDrag } from 'react-dnd' import { ItemTypes } from './Constants' export default function Card({ isDragging, text }) { const [{ opacity }, dragRef] = useDrag( () => ({ type: ItemTypes.CARD, item: { text }, collect: (monitor) => ({ opacity: monitor.isDragging() ? 0.5 : 1 }) }), [] ) return ( <div ref={dragRef} style={{ opacity }}> {text} </div> ) } ``` 請注意,HTML5 後端不支援觸控事件。因此它不適用於平板電腦和行動裝置。您可以將`react-dnd-touch-backend`用於觸控裝置。閱讀[文件](https://react-dnd.github.io/react-dnd/docs/backends/touch)。 ``` import { TouchBackend } from 'react-dnd-touch-backend' import { DndProvider } from 'react-dnd' class YourApp { <DndProvider backend={TouchBackend} options={opts}> {/* Your application */} </DndProvider> } ``` 這個codesandbox規定了我們如何正確使用React DND。 https://codesandbox.io/embed/3y5nkyw381?view=Editor+%2B+Preview&module=%2Fsrc%2Findex.tsx&hidenavigation=1 你可以看看React DND的[例子](https://react-dnd.github.io/react-dnd/examples)。 它們甚至有一個乾淨的功能,您可以使用 Redux 檢查內部發生的情況。 您可以透過為提供者新增 debugModeprop 來啟用[Redux DevTools](https://github.com/reduxjs/redux-devtools) ,其值為 true。 ``` <DndProvider debugMode={true} backend={HTML5Backend}> ``` 它提供了多種元件選項,我需要親自測試一下。總的來說,這看起來相當不錯,特別是如果你剛開始的話。 React DND 已獲得`MIT`許可,並在 GitHub 上擁有超過 20k Stars,這使其具有令人難以置信的可信度。 https://github.com/react-dnd/react-dnd Star React DND ⭐️ --- 5. [Cypress](https://github.com/cypress-io/cypress) - 快速測試瀏覽器中執行的內容。 -------------------------------------------------------------------- ![柏](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ybhbgvetu8tky7xiepdz.png) 近年來已經證明了測試的重要性,而 Jest 和 Cypress 等選項使其變得異常簡單。 但我們只會介紹 Cypress,因為它本身就很方便。 只需一張圖片就能證明 Cypress 值得付出努力。 ![柏](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ey0v3unpnblie1o610iv.png) 開始使用以下 npm 指令。 ``` npm install cypress -D ``` 如果您在專案中沒有使用 Node 或套件管理器,或者您想快速試用 Cypress,您始終可以[直接從 CDN 下載 Cypress](https://download.cypress.io/desktop) 。 一旦安裝並打開它。您必須使用`.cy.js`建立一個規範檔案。 ![規格文件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/077r7oilgyuf5j0chryv.png) 現在,您可以編寫並測試您的應用程式(範例程式碼)。 ``` describe('My First Test', () => { it('Does not do much!', () => { expect(true).to.equal(true) }) }) ``` Cypress 提供了多種選項,例如`cy.visit()`或`cy.contains()` 。由於我沒有廣泛使用 Cypress,因此您需要在其[文件](https://docs.cypress.io/guides/end-to-end-testing/writing-your-first-end-to-end-test)中進一步探索它。 如果它看起來很可怕,那麼請前往這個[為初學者解釋 Cypress 的](https://www.youtube.com/watch?v=u8vMu7viCm8&pp=ygUQY3lwcmVzcyB0dXRvcmlhbA%3D%3D)freeCodeCamp 教程。 Freecodecamp 影片確實是金礦 :D Cypress 在 GitHub 上擁有超過 45,000 顆星,並且在目前的 v13 版本中,它正在不斷改進。 https://github.com/cypress-io/cypress 星柏 ⭐️ --- [6.Refine](https://github.com/refinedev/refine) - 面向企業的開源 Retool。 ----------------------------------------------------------------- ![精煉](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7wsti2yfikrhc9nggov5.png) Refine 是一個元 React 框架,可以快速開發各種 Web 應用程式。 從內部工具到管理面板、B2B 應用程式和儀表板,它可作為建立任何類型的 CRUD 應用程式(例如 DevOps 儀表板、電子商務平台或 CRM 解決方案)的全面解決方案。 ![電子商務](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xry9381y4s36emgb9psr.png) 您可以在一分鐘內使用單一 CLI 命令進行設定。 它具有適用於 15 多個後端服務的連接器,包括 Hasura、Appwrite 等。 您可以查看可用的[整合清單](https://refine.dev/integrations/)。 ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7h9tbp4u3llh8ywgb8m8.png) 但最好的部分是,Refine `headless by design` ,從而提供無限的樣式和自訂選項。 由於該架構,您可以使用流行的 CSS 框架(如 TailwindCSS)或從頭開始建立樣式。 這是最好的部分,因為我們不希望最終受到與特定庫的兼容性的樣式限制,因為每個人都有自己的風格並使用不同的 UI。 開始使用以下 npm 指令。 ``` npm create refine-app@latest ``` 這就是使用 Refine 新增登入資訊的簡單方法。 ``` import { useLogin } from "@refinedev/core"; const { login } = useLogin(); ``` 使用 Refine 概述程式碼庫的結構。 ``` const App = () => ( <Refine dataProvider={dataProvider} resources={[ { name: "blog_posts", list: "/blog-posts", show: "/blog-posts/show/:id", create: "/blog-posts/create", edit: "/blog-posts/edit/:id", }, ]} > /* ... */ </Refine> ); ``` 您可以閱讀[文件](https://refine.dev/docs/)。 您可以看到一些使用 Refine 建立的範例應用程式: - [全功能管理面板](https://example.admin.refine.dev/) - [優化不同的用例場景](https://github.com/refinedev/refine/tree/master/examples)。 他們甚至提供模板,這就是為什麼這麼多用戶喜歡Refine。 你可以看到[模板](https://refine.dev/templates/)。 ![範本](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/87vbx5tqyicb9gmgirka.png) 他們在 GitHub 上擁有大約 22k+ 顆星。 https://github.com/refinedev/refine 星際精煉 ⭐️ --- 7. [Tremor](https://github.com/tremorlabs/tremor) - React 元件來建立圖表和儀表板。 ---------------------------------------------------------------------- ![樣品元件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hq6ehdstz94ya5kfvwl4.png) Tremor 提供了 20 多個開源 React 元件,用於建立基於 Tailwind CSS 的圖表和儀表板,使資料視覺化再次變得簡單。 ![社群](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dkwu1t43p0zfsmeehqxl.png) 開始使用以下 npm 指令。 ``` npm i @tremor/react ``` 這就是您如何使用 Tremor 快速建立東西。 ``` import { Card, ProgressBar } from '@tremor/react'; export default function Example() { return ( <Card className="mx-auto max-w-md"> <h4 className="text-tremor-default text-tremor-content dark:text-dark-tremor-content"> Sales </h4> <p className="text-tremor-metric font-semibold text-tremor-content-strong dark:text-dark-tremor-content-strong"> $71,465 </p> <p className="mt-4 flex items-center justify-between text-tremor-default text-tremor-content dark:text-dark-tremor-content"> <span>32% of annual target</span> <span>$225,000</span> </p> <ProgressBar value={32} className="mt-2" /> </Card> ); } ``` 這就是基於此生成的內容。 ![輸出](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7tvpu7r0rig522zeqae8.png) 您可以閱讀[文件](https://www.tremor.so/docs/getting-started/installation)。其間,他們在引擎蓋下使用混音圖標。 從我見過的各種元件來看,這是一個很好的起點。相信我! Tremor 還提供了一個[乾淨的 UI 工具包](https://www.figma.com/community/file/1233953507961010067)。多麼酷啊! ![使用者介面套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3jf4cwk5ybsc89dhz696.png) Tremor 在 GitHub 上擁有超過 14k 顆星,並有超過 280 個版本,這意味著它正在不斷改進。 https://github.com/tremorlabs/tremor 星震 ⭐️ --- 8. [Watermelon DB](https://github.com/Nozbe/WatermelonDB) - 用於 React 和 React Native 的反應式和非同步資料庫。 ------------------------------------------------------------------------------------------------ ![西瓜資料庫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sbofucs4kcaix7igjfch.png) 我不知道為什麼資料庫有這麼多選項;甚至很難全部數清。但如果我們使用 React,Watermelon DB 是一個不錯的選擇。即使在 4k+ 提交之後,它們仍然處於`v0.28`版本,這是一個相當大的問題。 Rocket.chat 使用 Watermelon DB,這給了他們巨大的可信度。 開始使用以下 npm 指令。 ``` npm install @nozbe/watermelondb ``` 您需要做的第一件事是建立模型和後續遷移(閱讀文件)。 ``` import { appSchema, tableSchema } from '@nozbe/watermelondb' export default appSchema({ version: 1, tables: [ // We'll add to tableSchemas here ] }) ``` 根據文件,使用 WatermelonDB 時,您正在處理模型和集合。然而,在 Watermelon 之下有一個底層資料庫(SQLite 或 LokiJS),它使用不同的語言:表格和欄位。這些一起稱為資料庫模式。 您可以閱讀有關[CRUD 操作的](https://watermelondb.dev/docs/CRUD)[文件](https://watermelondb.dev/docs/Installation)和更多內容。 https://github.com/Nozbe/WatermelonDB 明星 WatermelonDB ⭐️ --- 9. [Evergreen UI](https://github.com/segmentio/evergreen) - 按 Segment 劃分的 React UI 框架。 -------------------------------------------------------------------------------------- ![常青用戶介面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dkfdl3thy6cdukhxg92j.png) 沒有 UI 框架的清單幾乎是不可能的。有許多受歡迎的選項,例如 Material、Ant Design、Next UI 等等。 但我們正在報道 Evergreen,它本身就非常好。 開始使用以下 npm 指令。 ``` $ npm install evergreen-ui ``` [Evergreen Segment 網站](https://evergreen.segment.com/foundations)上顯示了任何使用者介面的基礎以及詳細的選項。 ![基礎](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/imir9z0siqqwh99p6lno.png) 它提供了很多元件,其中一些非常好,例如`Tag Input`或`File uploader` 。 ![標籤輸入](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yrsxzhzdemj49aeauc8j.png) ![文件上傳器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fckysg2iz6iz7c4st3as.png) 您可以看到 Evergreen UI 提供的所有[元件](https://evergreen.segment.com/components)。 https://github.com/segmentio/evergreen Star Evergreen UI ⭐️ --- 10. [React Spring](https://www.react-spring.dev/) - 流暢的動畫來提升 UI 和互動。 -------------------------------------------------------------------- ![反應彈簧](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ouigl2pr2rwbyj2whzli.png) ![流體動畫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eosf22k1notx3wa1pfpd.png) 如果您喜歡 React-Motion 但感覺過渡不流暢,那是因為它專門使用 React 渲染。 如果你喜歡 Popmotion,但感覺自己的能力受到限制,那是因為它完全跳過了 React 渲染。 `react-spring`提供了兩種選擇,試試看! 開始使用以下 npm 指令。 ``` npm i @react-spring/web ``` 這就是導入高階元件來包裝動畫的方法。 ``` import { animated } from '@react-spring/web' // use it. export default function MyComponent() { return ( <animated.div style={{ width: 80, height: 80, background: '#ff6d6d', borderRadius: 8, }} /> ) } ``` 由於以下程式碼和框,我決定嘗試 React Spring。令人驚訝的是,我們可以使用 React Spring 做很多事情。 https://codesandbox.io/embed/mdovb?view=Editor+%2B+Preview&module=%2Fsrc%2Findex.tsx&hidenavigation=1 您可以閱讀[文件](https://www.react-spring.dev/docs/getting-started)。 他們還提供了很多您可以學習的[範例](https://www.react-spring.dev/examples)。 ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/muzldxpw58tun2yyn18t.png) 它提供了大量的選項,例如`useScroll` ,它允許您建立滾動連結動畫。 例如,這個codesandbox告訴了`useScroll`的用法。 https://codesandbox.io/embed/b07dmz?view=Editor+%2B+Preview&module=%2Fsrc%2Findex.tsx&hidenavigation=1 React Spring 在 GitHub 上有大約 27k+ Stars。 https://github.com/pmndrs/react-spring Star React Spring ⭐️ --- 11. [React Tweet](https://github.com/vercel/react-tweet) - 將推文嵌入到你的 React 應用程式中。 -------------------------------------------------------------------------------- ![反應推文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9t2ktcvb8p6eitul8y9b.png) `React Tweet`可讓您在使用 Next.js、Create React App、Vite 等時將推文嵌入到 React 應用程式中。 該函式庫不需要使用 Twitter API。推文可以靜態呈現,從而無需包含 iframe 和額外的客戶端 JavaScript。 它是 Vercel 的開源專案。 開始使用以下 npm 指令。 ``` npm i react-tweet ``` 為了顯示推文,我們需要從 Twitter 的 API 請求資料。透過此 API 進行速率限制具有挑戰性,但如果您僅依賴我們提供的 SWR 端點 ( `react-tweet.vercel.app/api/tweet/:id` ),這是可能的,因為伺服器的IP 位址向Twitter 發出了許多請求API。這也適用於 RSC,其中 API 端點不是必需的,但伺服器仍然從相同 IP 位址發送請求。 為了避免 API 限制,您可以使用 Redis 或 Vercel KV 等資料庫快取推文。例如,您可以使用 Vercel KV。 ``` import { Suspense } from 'react' import { TweetSkeleton, EmbeddedTweet, TweetNotFound } from 'react-tweet' import { fetchTweet, Tweet } from 'react-tweet/api' import { kv } from '@vercel/kv' async function getTweet( id: string, fetchOptions?: RequestInit ): Promise<Tweet | undefined> { try { const { data, tombstone, notFound } = await fetchTweet(id, fetchOptions) if (data) { await kv.set(`tweet:${id}`, data) return data } else if (tombstone || notFound) { // remove the tweet from the cache if it has been made private by the author (tombstone) // or if it no longer exists. await kv.del(`tweet:${id}`) } } catch (error) { console.error('fetching the tweet failed with:', error) } const cachedTweet = await kv.get<Tweet>(`tweet:${id}`) return cachedTweet ?? undefined } const TweetPage = async ({ id }: { id: string }) => { try { const tweet = await getTweet(id) return tweet ? <EmbeddedTweet tweet={tweet} /> : <TweetNotFound /> } catch (error) { console.error(error) return <TweetNotFound error={error} /> } } const Page = ({ params }: { params: { tweet: string } }) => ( <Suspense fallback={<TweetSkeleton />}> <TweetPage id={params.tweet} /> </Suspense> ) export default Page ``` 您可以直接使用它,方法非常簡單。 ``` <div className="dark"> <Tweet id="1629307668568633344" /> </div> ``` 如果您不喜歡使用 Twitter 主題,您也可以使用多個選項建立自己的[自訂主題](https://react-tweet.vercel.app/custom-theme)。 例如,您可以建立自己的推文元件,但沒有回覆按鈕,如下所示: ``` import type { Tweet } from 'react-tweet/api' import { type TwitterComponents, TweetContainer, TweetHeader, TweetInReplyTo, TweetBody, TweetMedia, TweetInfo, TweetActions, QuotedTweet, enrichTweet, } from 'react-tweet' type Props = { tweet: Tweet components?: TwitterComponents } export const MyTweet = ({ tweet: t, components }: Props) => { const tweet = enrichTweet(t) return ( <TweetContainer> <TweetHeader tweet={tweet} components={components} /> {tweet.in_reply_to_status_id_str && <TweetInReplyTo tweet={tweet} />} <TweetBody tweet={tweet} /> {tweet.mediaDetails?.length ? ( <TweetMedia tweet={tweet} components={components} /> ) : null} {tweet.quoted_tweet && <QuotedTweet tweet={tweet.quoted_tweet} />} <TweetInfo tweet={tweet} /> <TweetActions tweet={tweet} /> {/* We're not including the `TweetReplies` component that adds the reply button */} </TweetContainer> ) } ``` 您可以閱讀[文件](https://react-tweet.vercel.app/#installation)。 您可以查看[React Tweet 的演示,](https://react-tweet-next.vercel.app/light/1761133168772489698)以了解它如何在頁面上呈現。 它們已發布`v3.2`版本,這表明它們正在不斷改進,並且[每週下載量超過 46k+](https://www.npmjs.com/package/react-tweet) 。 https://github.com/vercel/react-tweet Star React 推文 ⭐️ --- 12. [React 360](https://github.com/facebookarchive/react-360) - 使用 React 建立令人驚嘆的 360 度和 VR 內容。 ---------------------------------------------------------------------------------------------- ![反應 360](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/92546vucm4rnnseew2fi.png) 儘管 Facebook 已將其存檔,但許多開發人員仍然發現它足夠有用,因此繼續使用。 React 360 是一個函式庫,它利用大量 React Native 功能來建立在 Web 瀏覽器中執行的虛擬實境應用程式。 它使用 Three.js 進行渲染,並作為 npm 套件提供。透過將 WebGL 和 WebVR 等現代 API 與 React 的聲明性功能結合,React 360 有助於簡化建立跨平台 VR 體驗的過程。 開始使用以下 npm 指令。 ``` npm install -g react-360-cli ``` 涉及的事情有很多,但您可以使用 VrButton 加入重要的互動功能到您的 React VR 應用程式。 ``` import { AppRegistry, StyleSheet, Text, View, VrButton } from 'react-360'; state = { count: 0 }; _incrementCount = () => { this.setState({ count: this.state.count + 1 }) } <View style={styles.panel}> <VrButton onClick={this._incrementCount} style={styles.greetingBox}> <Text style={styles.greeting}> {`You have visited Simmes ${this.state.count} times`} </Text> </VrButton> </View> ``` 除了許多令人驚奇的東西之外,您還可以加入聲音。請參閱[使用 React 360 的 React Resources](https://reactresources.com/topics/react-360)範例。 您也可以閱讀 Log Rocket 撰寫的關於[使用 React 360 建立 VR 應用](https://blog.logrocket.com/building-a-vr-app-with-react-360/)程式的部落格。 這個codesandbox代表了我們可以使用React 360做什麼的一個常見範例。 https://codesandbox.io/embed/2bye27?view=Editor+%2B+Preview&module=%2Fsrc%2Findex.js&hidenavigation=1 https://github.com/facebookarchive/react-360 Star React 360 ⭐️ --- 13. [React Advanced Cropper](https://github.com/advanced-cropper/react-advanced-cropper) - 建立適合您網站的裁剪器。 ------------------------------------------------------------------------------------------------------- ![反應先進的作物](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x9b7o2lchxua4urkot79.png) ![反應先進的作物](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tc5328gj9v9yjbptu3nn.png) React Advanced Cropper 是一個高級庫,可讓您建立適合任何網站設計的裁剪器。這意味著您不僅可以更改裁剪器的外觀,還可以自訂其行為。 它們仍處於測試版本,這意味著 API 可能會在未來版本中發生變化。 簡單的用例是設計軟體和裁剪圖像表面以獲得進一步的見解。 他們有很多選擇,因此值得。 ![選項](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nt5br00qyymlllmjlowk.png) ![選項](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/atvlbxjowv1isjoi3p6m.png) 開始使用以下 npm 指令。 ``` npm install --save react-advanced-cropper ``` 您可以這樣使用它。 ``` import React, { useState } from 'react'; import { CropperRef, Cropper } from 'react-advanced-cropper'; import 'react-advanced-cropper/dist/style.css' export const GettingStartedExample = () => { const [image, setImage] = useState( 'https://images.unsplash.com/photo-1599140849279-1014532882fe?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1300&q=80', ); const onChange = (cropper: CropperRef) => { console.log(cropper.getCoordinates(), cropper.getCanvas()); }; return ( <Cropper src={image} onChange={onChange} className={'cropper'} /> ) }; ``` 您可以閱讀[文件](https://advanced-cropper.github.io/react-advanced-cropper/docs/intro),它們提供了[20 多個自訂選項](https://github.com/advanced-cropper/react-advanced-cropper?tab=readme-ov-file#cropper)。 他們主要提供三種類型的[裁剪器選項](https://advanced-cropper.github.io/react-advanced-cropper/docs/guides/cropper-types/):固定、經典和混合以及範例和程式碼。 您可以使用 React Advanced Cropper 製作一些令人興奮的東西來向世界展示:) https://github.com/advanced-cropper/react-advanced-cropper Star React 進階裁剪器 ⭐️ --- 14. [Mobx](https://github.com/mobxjs/mobx) - 簡單、可擴展的狀態管理。 --------------------------------------------------------- ![行動裝置](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/od2isnsvbr1y349cpcnb.png) MobX 是一個經過驗證的基於訊號的函式庫,可透過函數反應式程式設計簡化和擴展狀態管理。它提供了靈活性,使您能夠獨立於任何 UI 框架來管理應用程式狀態。 這種方法會產生解耦、可移植且易於測試的程式碼。 以下是使用 MobX 的任何應用程式中處理事件的方式。 ![事件架構](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3k0uxde1tnj8y8xizo8c.png) 圖片來自文件 開始使用以下 npm 指令。 ``` npm install mobx-react --save // CDN is also available ``` 這就是它的樣子。 ``` import { observer } from "mobx-react" // ---- ES6 syntax ---- const TodoView = observer( class TodoView extends React.Component { render() { return <div>{this.props.todo.title}</div> } } ) // ---- ESNext syntax with decorator syntax enabled ---- @observer class TodoView extends React.Component { render() { return <div>{this.props.todo.title}</div> } } // ---- or just use function components: ---- const TodoView = observer(({ todo }) => <div>{todo.title}</div>) ``` 您可以使用 props、全域變數或使用 React Context 在觀察者中使用外部狀態。 您可以閱讀[有關 React Integration](https://mobx.js.org/react-integration.html)和[npm docs](https://www.npmjs.com/package/mobx-react#api-documentation)的文件。 您也可以閱讀[MobX 和 React 的 10 分鐘互動介紹](https://mobx.js.org/getting-started)。 MobX 在 GitHub 上擁有超過 27k 顆星,並在 GitHub 上被超過 140K 開發者使用。 https://github.com/mobxjs/mobx 明星 Mobx ⭐️ --- 15. [React Virtualized](https://github.com/bvaughn/react-virtualized) - 渲染大型清單和表格資料。 ------------------------------------------------------------------------------------ ![反應虛擬化](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/znt47ig09aebglto0915.png) 開始使用以下 npm 指令。 ``` npm install react-virtualized --save ``` 以下是如何在網格中使用 ColumnSizer 元件。探索演示(文件)以詳細了解可用選項。 ``` import React from 'react'; import ReactDOM from 'react-dom'; import {ColumnSizer, Grid} from 'react-virtualized'; import 'react-virtualized/styles.css'; // only needs to be imported once // numColumns, numRows, someCalculatedHeight, and someCalculatedWidth determined here... // Render your list ReactDOM.render( <ColumnSizer columnMaxWidth={100} columnMinWidth={50} columnCount={numColumns} width={someCalculatedWidth}> {({adjustedWidth, getColumnWidth, registerChild}) => ( <Grid ref={registerChild} columnWidth={getColumnWidth} columnCount={numColumns} height={someCalculatedHeight} cellRenderer={someCellRenderer} rowHeight={50} rowCount={numRows} width={adjustedWidth} /> )} </ColumnSizer>, document.getElementById('example'), ); ``` 您可以閱讀[文件](https://github.com/bvaughn/react-virtualized/tree/master/docs#documentation)和[演示](https://bvaughn.github.io/react-virtualized/#/components/List)。 他們提供了 React-window 作為輕量級的替代方案,但這個在發布和明星方面更受歡迎,所以我介紹了這個選項。您可以閱讀哪個選項更適合您: [React-Window 與 React-Virtualized 有何不同?](https://github.com/bvaughn/react-window?tab=readme-ov-file#how-is-react-window-different-from-react-virtualized) 。 它被超過 85,000 名開發人員使用,並在 GitHub 上擁有超過 25,000 顆星。它還擁有令人印象深刻的[170 萬+ 每週下載量](https://www.npmjs.com/package/react-virtualized)。 https://github.com/bvaughn/react-virtualized Star React 虛擬化 ⭐️ --- 16.React [Google Analytics](https://github.com/react-ga/react-ga) - React Google Analytics 模組。 ---------------------------------------------------------------------------------------------- ![反應Google分析](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a6lh8m8zussnyn32togy.png) 這是一個 JavaScript 模組,可用於在使用 React 作為前端程式碼庫的網站或應用程式中包含 Google Analytics 追蹤程式碼。 該模組對我們如何在前端程式碼中進行追蹤有一定的看法。我們的 API 比核心 Google Analytics 庫稍微詳細一些,以使程式碼更易於閱讀。 開始使用以下 npm 指令。 ``` npm install react-ga --save ``` 您可以這樣使用它。 ``` import ReactGA from 'react-ga'; ReactGA.initialize('UA-000000-01'); ReactGA.pageview(window.location.pathname + window.location.search); <!-- The core React library --> <script src="https://unpkg.com/[email protected]/dist/react.min.js"></script> <!-- The ReactDOM Library --> <script src="https://unpkg.com/[email protected]/dist/react-dom.min.js"></script> <!-- ReactGA library --> <script src="/path/to/bower_components/react-ga/dist/react-ga.min.js"></script> <script> ReactGA.initialize('UA-000000-01', { debug: true }); </script> ``` 執行`npm install` `npm start`並前往`port 8000 on localhost`後,您可以閱讀[文件](https://github.com/react-ga/react-ga?tab=readme-ov-file#installation)並查看[演示](https://github.com/react-ga/react-ga/tree/master/demo)。 它每週的下載量超過 35 萬次,在 GitHub 上擁有超過 5,000 顆星(已存檔)。 https://github.com/react-ga/react-ga Star React Google Analytics ⭐️ --- 17.react [-i18next](https://github.com/i18next/react-i18next) - React 的國際化做得很好。 ------------------------------------------------------------------------------- ![反應-i18next](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xrxn9omsv79bzy9j9mr4.png) 無需更改 webpack 配置或加入額外的 babel 轉譯器。 開始使用以下 npm 指令。 ``` npm i react-i18next ``` 我們來比較一下程式碼結構。 > 在使用react-i18next之前。 ``` ... <div>Just simple content</div> <div> Hello <strong title="this is your name">{name}</strong>, you have {count} unread message(s). <Link to="/msgs">Go to messages</Link>. </div> ... ``` > 使用react-i18next後。 ``` ... <div>{t('simpleContent')}</div> <Trans i18nKey="userMessagesUnread" count={count}> Hello <strong title={t('nameTitle')}>{{name}}</strong>, you have {{count}} unread message. <Link to="/msgs">Go to messages</Link>. </Trans> ... ``` 您可以閱讀[文件](https://react.i18next.com/)並前往[Codesandbox 的互動式遊樂場](https://codesandbox.io/s/1zxox032q)。 該工具已被超過 182,000 名開發人員使用,在 GitHub 上擁有超過 8,000 顆星。軟體包中令人印象深刻的 3400k+ 下載量進一步鞏固了它的可信度,使其成為您下一個 React 專案的絕佳選擇。 您也可以閱讀 Locize 關於[React Localization - Internationalize with i18next](https://locize.com/blog/react-i18next/)的部落格。 https://github.com/i18next/react-i18next 明星react-i18next ⭐️ --- 哇!如此長的有用專案清單。 我知道您有更多想法,分享它們,讓我們一起建造:D 現在就這些了! 在開展新專案時,開發人員經驗至關重要,這就是為什麼有些專案擁有龐大的社區,而有些則沒有。 React 社群非常龐大,所以成為這些社群的一部分,並使用這些開源專案將您的專案提升到一個新的水平。 祝你有美好的一天!直到下一次。 在 GitHub 上關注我。 https://github.com/Anmol-Baranwal 請關注 CopilotKit 以了解更多此類內容。 https://dev.to/copilotkit --- 原文出處:https://dev.to/copilotkit/libraries-you-should-know-if-you-build-with-react-1807

100% AI 驅動的 Web 開發工作流程,與 Devin 一樣出色:MAGE x Aider

長話短說 ---- [Devin](https://www.youtube.com/watch?v=fjHtjT7GO1c) ,這位自稱「第一個」完全自主的軟體工程師剛剛出現,並引起了很多關注。 它尚未公開,但透過幾個開源工具,您現在可以獲得類似的 Web 開發體驗,而且成本可能只是一小部分。 {% 嵌入 https://www.youtube.com/watch?v=DXunbNBpgZg %} 在其 CLI 中使用[Wasp 的 AI 功能](https://wasp.sh),您可以透過簡單的提示產生全端 Web 應用程式程式碼庫。然後,在[Aider](https://aider.chat)的幫助下透過加入功能和除錯來迭代它。 在這兩個人工智慧代理的幫助下,您可以增強全端應用程式的開發,而無需編寫一行程式碼(如果您不想)。 請繼續閱讀有關如何開始的詳細說明! --- ![星星](https://res.cloudinary.com/practicaldev/image/fetch/s--2jk6M804--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j3a8gkl9fcs0a8rl4zsq.gif) 順便說一句,Wasp 是建立全端 Web 應用程式的最快方法,而且它也恰好內建了 AI 生成 - 而且它是免費和開源的! 您可以透過[在 GitHub 上為我們的儲存庫加註星標](https://www.github.com/wasp-lang/wasp)來支持我們。它幫助我們建立更多東西並創造更多像這樣很酷的內容🙏 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1hk4emh8rr8q4j35sxud.gif) {% cta https://www.github.com/wasp-lang/wasp %} 連 Ron 也會在 GitHub 上為 Wasp 加註星標 🤩 {% endcta %} --- 德文到底是誰? ------- 您可能已經看到和聽過圍繞 Devin 的炒作,他自稱是「第一個」完全自主的軟體工程師。 如果沒有,請觀看下面的宣傳影片: {% 嵌入 https://www.youtube.com/watch?v=fjHtjT7GO1c %} 儘管 Devin 絕對不是同類中的第一個人工智慧編碼助手,但它的推出仍然引起了許多人的注意。簡而言之,這就是 Devin 所做的: - 接受提示 - 制定逐步計劃 - 在具有程式碼編輯器、終端、瀏覽器和聊天介面的時尚 UI 中展示其工作 - 能夠迭代現有的程式碼庫 儘管有其他類似的人工智慧編碼代理,其中一些像 GPT-Pilot 是開源的,但 Devin 使用內建所有必要工具的流暢 UI 使其脫穎而出。此外,它能夠迭代現有程式碼庫,這使其與大多數類似工具(Aider 除外)區分開來。 那麼,德文真的那麼令人印象深刻嗎? 是和不是。正如著名 AI YouTuber [Matthew Berman](https://www.youtube.com/@matthew_berman)在他關於 Devin 的影片中指出的那樣,Devin 最令人印象深刻的事情可能是他們的發布的成功。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y5mrfmizjkew07qrd8qw.png) 但伯曼也指出了一些與他們的行銷主張不一致的地方: 1. Devin 絕對不是同類中的第一個。 [Mage](https://useMage.ai) 、 [Aider](https://aider.chat)和[GPT-Pilot](https://github.com/Pythagora-io/gpt-pilot)等類似工具已經存在。 2. 他們對效能基準的比較(如上圖所示)並不能真正被認真對待,因為Devin 是一個可以迭代和執行多個任務的代理,而它所比較的 LLM,如GPT-4,只是「零樣本」 (即他們嘗試一次才能得到正確的答案)。為了公平比較,Devin 應該與其他代理人進行比較,例如 GPT-Pilot、MetaGPT、Mage 等。 另外,Devin 實際上是建立在 OpenAI 的 GPT-4 API 之上的。所以,是的,他們在其之上建置的一些工具非常令人印象深刻,並且將加快編碼工作流程,但底層模型與像您和我這樣的開發人員可以存取的東西完全相同。 這意味著,透過結合幾個可用的開源工具,您現在可以獲得與 Devin 非常相似的結果,而無需等待早期預覽存取,並且成本可能只是其一小部分。 現在就讓我們來看看吧! Wasp AI x Aider — 全端 Web 應用程式的開源「Devin」替代品 ------------------------------------------ 幾個月前,我們發布了[Mage](https://usemage.ai) ( **Magic** **App** **Generator** ),這是一個實驗平台,用於透過簡單的提示生成全端 Web 應用程式。自發布以來,Mage 已被用來產生超過 40k 個應用程式! ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxzoa3be0u5qghqmvpd8.png) Mage 使用[Wasp(一個全端 React、Node 和 Prisma 框架)](https://wasp.sh)來產生比大多數編碼助理更好的全端應用程式。到底是為什麼呢?這是因為 Wasp 使用聲明性設定檔來定義應用程式的功能。 這個設定檔為Wasp 的編譯器提供了將客戶端和伺服器程式碼「黏合」在一起所需的指令,並處理一堆樣板程式碼,因此您和AI 都不必處理諸如身份驗證、路由、端點、伺服器之類的編碼配置等 ``` // wasp config file app TodoApp { wasp: { version: "^0.13.0" }, auth: { userEntity: User, methods: { usernameAndPassword: {} }, } } entity User {=psl id Int @id @default(autoincrement()) tasks Task[] psl=} // rest of the config file... ``` 查看上面的範例,了解如何使用 Wasp 編寫全端 Auth。很容易,對吧?現在想像一下,對於 Mage 或任何其他人工智慧編碼助理來說,編寫 Wasp 程式碼是多麼容易。 另外,由於 Wasp 設定檔的結構已經類似於一組指令,因此它允許 Mage 以與 Devin 類似的方式建立計劃。 這就是 Mage 真正的閃光點,它可以快速且廉價地建立功能齊全的全端 Web 應用程式原型。 Mage 的唯一缺點是它在終端中不可用,而且您無法進一步迭代生成的程式碼庫。 現在情況改變了。隨著新的 Wasp 更新,Mage 的所有功能都被打包到 CLI 中。您只需[安裝 Wasp](https://wasp-lang.dev/docs/quick-start)並執行`wasp new` ,您就可以透過命令列提示產生一個新的全端應用程式! ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uthik90clhytebvyndh0.png) 之後,您可以使用[Aider](https://aider.chat) ,這是一個命令列工具,可讓您與 GPT-3.5/GPT-4 進行配對編程,以迭代生成的程式碼庫並建立一系列很酷的新功能。 還不相信嗎?觀看這個很酷的宣傳影片,向您展示這一切是如何運作的: {% 嵌入 https://www.youtube.com/watch?v=DXunbNBpgZg %} 如果這看起來很酷,並且您想在這些工具的幫助下開始建立自己的全端 Web 應用程式,請按照以下說明進行操作! CLI 中的 Wasp AI -------------- [安裝 Wasp](https://wasp-lang.dev/docs/quick-start)後,前往終端並執行`wasp new` 這樣做將為您提供一個可供選擇的全端入門模板清單。你會想要: - 從選項清單中選擇`[5] ai-generated` - 輸入您的應用程式的描述 - 選擇您想要用於這一代的 GPT 模型和創造力水平 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iyyrvrjg4ykvftutp5k2.png) 使用這些生成設定可能會產生不同的結果,因此,如果生成的應用程式不是您第一次尋找的內容,請調整它們並重試。 並且不必太擔心透過 OpenAI API 產生的成本。由於 Wasp 利用 DSL 並為我們管理大量樣板文件,因此它顯著減少了 GPT 必須產生的程式碼量。 例如,當我們混合使用 GPT4 和 GPT3.5(預設選項)時,一個具有 Wasp AI 的應用程式通常消耗大約 25k 到 60k 代幣,每個應用程式大約消耗**0.1 到 0.2 美元**!如果我們只使用 GPT4 來執行它,那麼成本是 10 倍,這意味著它將花費大約**1 到 2 美元**。這仍然比大多數其他 AI 編碼代理便宜得多,後者每代的成本通常約為 15-40 美元。 🤯 哦,「gpt-4-1106-preview」指的是 OpenAI 的新 GPT-4-turbo 模型。因此,它比完全使用 GPT-4 更快、更便宜。 Wasp AI(和[Mage](https://usemage.ai) )使用 GPT-4 進行規劃 + GPT-3.5-turbo 進行程式碼生成的組合,我們發現它對於簡單的應用程式來說效果出奇的好。如果您的目標是複雜的應用程式,我們建議完全使用 GPT-4,因為它能夠更好地處理更高的複雜性。請注意,GPT-4 將需要更長的時間。 繼續與 AI 迭代…der ------------- 在 Mage 的初始版本中,我們收到了很多問題,詢問是否有“除錯助手”,或者在初始輸出後繼續使用 AI 生成更多功能的方法。 雖然 Wasp AI 無法做到這一點,但我們開始探索其他具有除錯功能的 AI 編碼助手,最終我們非常喜歡[Aider 的](https://aider.chat/)工作流程和效能。另外,除了尚未向公眾發布的 Devin 之外,Aider 是目前唯一允許您迭代現有程式碼庫的 AI 編碼工具。 **所以,這使得 Wasp AI + Aider 成為完美的組合!** --- ![星星](https://res.cloudinary.com/practicaldev/image/fetch/s--2jk6M804--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j3a8gkl9fcs0a8rl4zsq.gif) 順便說一句,Wasp 是免費且開源的,所以如果您喜歡我們正在做的事情,請考慮[在 Github 上給我們一顆星](https://github.com/wasp-lang/wasp)! ![黃蜂](https://res.cloudinary.com/practicaldev/image/fetch/s--5pwnEx10--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lz3ok1dpfkscsoo0n2om.gif) {% cta https://www.github.com/wasp-lang/wasp %} ⭐️ 丟黃蜂一顆星星 🙏 {% endcta %} --- 使用 Wasp AI 產生全端應用程式後,您可以透過 Aider 使用自然語言來產生新功能或偵錯目前程式碼中的問題。 就是這樣: 1. 安裝[幫助](https://aider.chat) ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/avh771m902u6ukkbd1p5.png) 2. 在 Wasp 專案目錄中的命令列中執行`aider` ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ut16cyi6tlouuk9529tb.png) 3. `/add`您希望 Aider 使用的文件 4. 告訴 Aider 你想要它做什麼,例如在表單中加入“小睡次數”字段 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/af0vm9ngfilbgj9170ik.png) 5. 然後,Aider 將規劃一個行動方案,並將這些變更作為 git 提交應用程式。如果您不喜歡更改,請執行`/undo`撤銷提交 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4t0w7txe4xjsealfczke.png) 6. 如果您在嘗試使用`wasp start`執行程式碼時遇到錯誤,請將錯誤複製並貼上到聊天中,讓 Aider 為您解決。確保您已將錯誤引用的文件新增至聊天(請參閱步驟 3)! ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u8nc9sty41xbgrm7xwfr.png) 7. 如果您在使用 Aider 時需要更多幫助,請查看他們的[網站](https://aider.chat)或在 Aider 中執行`/help`以獲取命令列表 未來就在這裡 ------ 透過[Wasp AI](https://wasp.sh) ,我們最終將 Mage 的 AI 輔助全端應用腳手架能力加入到 Wasp 的 CLI 中。利用 GPT-4 和其他 OpenAI 模型的強大功能,用它來啟動您的下一個全端應用程式創意。 如果您想在 AI 幫助下繼續產生功能或直接從終端進行偵錯,請使用我們上面概述的 Aider 來保持流程繼續進行。 編碼的未來確實就在這裡。嘗試一下,讓我們知道您的想法! --- 原文出處:https://dev.to/wasp/a-100-ai-driven-workflow-thats-probably-as-good-as-devin-4c67

讓我們將函數式程式設計引入 OOP 程式碼庫

時間越長,我就越成為函數式程式設計的愛好者。即使當我在 OOP 程式碼庫中工作時,我也會嘗試應用旨在簡化程式碼並更輕鬆地預測結果的小概念。身為 Ruby 專家,我也喜歡使用功能程式碼編寫單元測試是多麼簡單。 本文的目的是分享我對函數式程式設計概念的看法,並提出一種可以在已編寫的 OOP 程式碼中使用函數式概念的方法。希望我們能夠停止爭論哪種範式更好,並開始編寫好的想法,每次都能產生更好的程式碼! 目錄 -- - [一開始,有函數式編程](#in-the-beginning-there-was-functional-programming) - [進入OOP,這個範式是什麼?](#entering-oop-what-is-this-paradigm) - [什麼是類別以及我們如何以不同的方式思考它](#what-is-a-class-and-how-can-we-think-about-it-differently) - [變異還是不變異:什麼是不變性](#to-mutate-or-not-to-mutate-what-is-immutability) - [床下的怪物:有什麼副作用](#the-monster-under-the-bed-what-are-side-effects) - [隔離一切:什麼是純函數](#isolate-everything-what-are-pure-functions) - [使用函數式模式而不需要完整的 haskell](#using-functional-patterns-without-going-full-haskell) - [結論](#conclusion) 一開始,有函數式編程 ---------- ![功能性](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hpg7b5lx6czu67jv9e07.png) 函數式程式設計範式於 1958 年隨著第一個 Lisp 語言的出現而出現(美好的時光)。它的根源可以追溯到 Alonzo Church 的 lambda 演算。函數式程式設計的核心原則圍繞著最小化對程式碼庫中狀態的依賴。 與允許狀態但強調封裝的物件導向程式設計 (OOP) 不同,函數式程式設計師努力優先編寫無狀態元件。這種方法鼓勵建立獨立於外部狀態變數的程式碼。 此外,即使引入了狀態,在編寫狀態時也必須考慮不變性、函數的純度,甚至避免副作用。隨著本文的深入,所有這些概念都將進一步介紹。 進入OOP,這個範式是什麼? -------------- ![打開](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/em6b2ejnoml80awxyrhw.png) OOP,或更廣為人知的名稱為“物件導向程式設計”,是一種可以追溯到 1967 年的範式。其最偉大的代表是 Simula、Smalltalk 和 Java。背後的思想過程是透過強制封裝實踐來將這些狀態以及修改它們的任何行為分組到公共「實體」或「物件」下,從而減少「全局」狀態的數量。 事實上,「物件導向程式設計」這個名字多年來一直被廣泛討論。 OOP 的建立者之一 Alan Key 實際上希望更多地關注該範例的訊息傳遞方面。這意味著我們應該強調封裝並允許物件之間進行狀態和行為的通訊。也許在不同的宇宙中,我們可以擁有「面向訊息的程式」。然而,OOP 這個名字已經經久不衰,而我們就在這裡! 我不知道你怎麼想,但是這個考慮範式的另一個可能名稱的簡單過程讓我的思維變得瘋狂,重新思考了一些概念,並實際上簡化了我建置軟體的方式。 什麼是類別以及我們如何以不同的方式思考它 -------------------- ![什麼是類](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/70x9cp26qi2cvx13dm3q.png) 我想每個人都聽過那個經典的講座,其中我們學到了“動物”類,其中包括“狗”類,對嗎?你可能聽過同樣的話(至少我聽過)。 > 類別是現實世界中實體的藍圖,描述其特徵和操作。 雖然不正確,但我想建議稍微改變一下單字的用法,以幫助澄清封裝,以便更好地理解,就像它對我所做的那樣。讓我們考慮以下新引文: > 類別是一種封裝狀態和在該狀態上操作的行為的方法。 這個簡單的字的改變確實讓我的思想改變了。我不再嘗試將類別視為現實世界的實體,而是開始簡單地將其視為將具有相似上下文的狀態分組在一起並公開對這些狀態進行操作的函數的另一種方式。我希望這個小小的改變也能幫助你回顧自己的概念! 以這種方式抽象化這個概念的重要性是,在從具有不同結構(例如模組)的語言中讀取程式碼時變得熟練。我們可以觀察到這段 OOP 程式碼是用 typescript 寫的: ``` class Github { private _url: string; privale _repo: string; private _username: string; constructor(url: string, repo: string, username: string) { this._repo = repo this._username = username this._url = url } public createRepo(name: string): void { // TODO: do stuff here using the provided state in _url, _repo and _username } } ``` 與此 Elixir 程式碼完全等效,即使 Elixir 程式碼使用“模組”而不是“類別”: ``` defmodule Github do @url "" @repo "" @username "" defstruct url: @url, repo: @repo, username: @username def new(url, repo, username) do %Github{url: url, repo: repo, username: username} end def create_repo(%Github{repo: repo, username: username}, name) do # TODO: do stuff here using the provided state in url, repo, and username end end ``` 接下來我們將研究一些功能概念並進一步討論這些範例的合併,讓我們開始吧! 變異還是不變異:什麼是不變性 -------------- ![不變性](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4fotff1cbifqi2c5ubtb.png) 現在我們正在達到第一個真正的功能概念,而且是一個非常重要的概念,我可以補充一下(一切都在這裡計劃)!為了正確理解不變性,讓我們回顧一下在程式設計中處理值的方式: 通常,我們將值綁定到變數,以便稍後可以對它們進行操作,對嗎?就像簡單的事情 ``` # Bounding values to variables name = 'Cherry' age = 23 # Operating on it and bounding to another variable year_born = Time.now.year - age # Printing it puts "#{name} has #{age} years old and was born at #{year_born}" ``` 對於這些變數,透過更新其值來更改原始變數是很常見的,但這裡缺少的是:修改變數是一種**破壞性**操作。 但為什麼?好吧,讓我們想像一下多個操作(函數或程式碼區塊)在不同時刻和頻率修改相同變數。在這種情況下,我們會產生很多問題,例如: - **1. 無法對操作重新排序或根本無法更改它們:**當我們有如此多的依賴程式碼時,甚至很難對程式碼進行重新排序或更改,因為所有內容都綁定到特定的更改順序。 - **2. 理解程式碼在做什麼的心理負擔:**雖然這是個人觀點,但我認為這是一個廣受認可的觀點。高度可變的程式碼很容易變得混亂且難以理解資料流,需要除錯器等工具來逐步完成轉換。 - **3. 測試時的困難:**模擬函數轉換的特定狀態確實很困難,這將逐漸擴展您的單元測試,直到它們不再是單元。 不變性可以定義為避免更改(或變異)程式內任何變數的做法。儘管根據語言的不同,我們可能需要做出讓步並改變一些控制變數,但這裡要學到的總體教訓是: > 我們應該不惜一切代價避免改變沒有定義範圍的變數。 透過這句話,我的意思是可以在函數內建立作用域變數並在那裡對其進行變異。然而,一旦您將這個可變變數傳遞給另一個函數,您就會增加改變相同變數的目標數量,並且您將慢慢失去控制。這正是我們想要避免的情況! 床底下的怪物:有什麼副作用 ------------- ![副作用](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yb1osy6ziacyc2l12h6v.png) 每當有人提出這個話題來討論時,這個話題就會引起很大的熱度。我可能不會涵蓋這個主題的每一個細微差別,但我一定會向您解釋它們是什麼以及我如何在我自己的軟體中管理副作用,好嗎? 那麼,副作用就是透過呼叫協定(HTTP、WebSocket、GraphQL 等)甚至操作 stdin/stdout 與外部資源(或「外部世界」)互動的每一次計算。是的,我知道,即使是我們無害的`print`也會在這裡受到指責。 😔 但與變異性不同的是,我們不應該盡可能避免使用它,而應該將其隔離在單獨處理副作用的特定函數中。這樣,我們將程式碼分為「不執行任何副作用的函數」和「執行副作用的函數」。但為什麼要擔心這種分離呢? 每次我們觸發對「外部世界」的任何操作時,我們都會失去對這個特定計算部分可能發生的情況的控制(例如在執行 HTTP 呼叫時,伺服器可能會關閉或可能根本不存在)。其他問題包括測試困難和程式碼可預測性降低。 由於我們無法編寫沒有副作用的任何現實世界軟體,因此一般建議是將其聚集成小函數,透過對錯誤的適當抽象來單獨處理它。這樣,就可以只測試我們 100% 控制的函數,並模擬所有執行副作用的函數。 例如,請考慮以下執行 HTTP 請求的函數以及轉換從該請求傳回的資料的小函數。 ``` require 'faraday' module MyServiceModule # This function perform side effects def perform_http_request conn = Faraday.new(url: "fakeapi.com") begin response = conn.get {ok: true, data: response.body} rescue => e {ok: false, error: e} end end # These functions doens't perform any side effects def upcase_name(name) return '' unless name.is_a?(String) name.upcase end def retrieve_born_year(age) return 0 unless age.is_a?(Integer) Time.now.year - age end end ``` > 看到我怎麼說「錯誤周圍的抽象」了嗎?這正是上面的程式碼範例中實現的,而不是讓異常在我們針對雜湊抽象的程式碼中冒泡。 在使用「副作用」和「無副作用」之間的明確定義來定義這些函數之後,很容易預測程式碼中會發生什麼,也更容易測試,如下所示: ``` require 'minitest/autorun' class TestingStuff < Minitest::Test def test_upcase_name assert_equal MyServiceModule.upcase_name "cherry", "CHERRY" assert_equal MyServiceModule.upcase_name "kalane", "KALANE" assert_equal MyServiceModule.upcase_name "Thales", "THALES" end def test_retrieve_born_year Time.stub :now, Time.new(2024, 3, 5) do assert_equal MyServiceModule.retrieve_born_year 23, 2001 assert_equal MyServiceModule.retrieve_born_year 20, 2004 assert_equal MyServiceModule.retrieve_born_year 14, 2010 end end end ``` 這個策略真的很棒,因為您甚至不需要在測試時擔心副作用部分,只需為實際執行某些操作的程式碼轉換部分編寫斷言,您最終會得到更好的測試,真正驗證重要的內容您的程式碼庫的一部分!整齊吧? 隔離一切:什麼是純函數 ----------- ![純函數](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bgnpfyig36sssuio9qpy.png) 現在是時候總結到目前為止所獲得的所有知識了。在前面的範例中,我們觀察到程式碼分為「副作用」和「無副作用」。我們還看到了這些功能如何更容易測試,並且我們的主要轉換業務邏輯應該保持隔離。您想知道這些函數叫什麼嗎?它們是**純函數**! 讓我們檢查純函數的正確形式定義並逐步探索這個概念。 > 純函數是尊重不變性、不執行任何副作用並且在給定相同參數的情況下傳回相同輸出的函數。 基本上,純函數遵循我們之前提到的所有原則,而且它們總是為相同的參數產生相同的返回。讓我們來看看之前的函數。 ``` def upcase_name(name) return '' unless name.is_a?(String) name.upcase end upcase_name('cherry') # => Will be *always* CHERRY ``` 使用純函數,我們可以輕鬆定義多個斷言,因為我們不受任何需要大量模擬的上下文的約束。我們只需用靜態值傳遞所需的參數,就這樣! 由於純函數非常小且可組合,因此它們的數量增加得非常快。為了解決這個問題,像 Elixir 這樣的函數式語言提供了像管道這樣的組合運算符,這使得按順序執行多個純函數變得非常容易。 ``` "cherry " |> trim |> upcase # => "CHERRY" ``` > 管道運算子源自 Bash 等函數。您可以在這裡閱讀更多相關資訊:\[ <https://dev.to/cherryramatis/linux-filters-how-to-streamline-text-like-a-boss-2dp4#what-is-a-pipeline> \] 使用函數式模式而不需要完整的 haskell ---------------------- ![都是功能啊](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/42ndx4tuvrs35q2woepg.png) 我一直害怕學習函數範式,因為社群透過使用現成的句子和大概念讓每個試圖學習一些小技巧的人變得非常複雜。在掌握了許多函數式語言並嘗試盡可能多地學習之後,我的目標是簡化這些概念,最重要的是,提倡在 OOP 程式碼中使用函數式概念。 應用純函數(或純方法,如果您願意)、不變性和副作用分離可以使您的 OOP 程式碼看起來更乾淨和解耦。你不需要知道什麼是 monad 或如何在 Haskell 中手動編寫編譯器;您可以使用簡單而有效的函數概念來堅持使用 Ruby on Rails! 我希望透過這篇小文章(以及本系列中的文章),無論您選擇哪種語言和框架,您都可以透過可組合性和簡單性來改進您的程式碼庫。 結論 -- 這篇文章是我嘗試使函數範式的知識民主化(在我的能力和專業知識範圍內)。需要強調的是,我不是函數式專家,本文針對的是了解 OOP 並對函數式程式設計感興趣的初學者。我希望它有用,並且我願意提供任何需要的幫助。願原力與你同在🍒 --- 原文出處:https://dev.to/cherryramatis/ending-the-war-or-continuing-it-lets-bring-functional-programming-to-oop-codebases-3mhd

100 多個專案創意

**編輯**:大家好!在對本文做出驚人反應後,我建立了一個名為「每週專案俱樂部」的專案。每週您的收件匣都會收到需要解決的問題。你可以努力解決問題,並且你將得到整個俱樂部的幫助,讓你走上正軌。了解更多並[在這裡](https://weeklyproject.club)註冊! 有一天我注意到一個模式。我注意到很多人都在努力 學習編程,但他們心中沒有特定的目標。我已經討論過如何了解您想要學習程式設計的原因可以幫助您選擇要學習的語言[!](https://pickaframework.com/articles/why/) ,以及如何實際做出決定([在這裡!](https://pickaframework.com/feature_fishing/) )但是專案有什麼幫助呢? 當我指導程式設計師時,我發現有一個專案可以幫助排除其他一些幹擾,例如想知道你是否使用了正確的語言。透過專注於一個特定的目標,你就不用那麼費力去擔心*這*是否正是你應該使用的語言。結果是你建立了一些簡潔的東西,並且一路上你學到了一些東西! 2隻鳥,1塊石頭。 這就是為什麼我為初學者程式設計師策劃了這個專案清單。許多人列出了大量的專案來學習編程,但很少按照難度進行組織。我瀏覽了幾個流行的程式設計專案想法清單。如果您想查看完整列表,可以在頁面底部找到來源。 我將其分為教程和想法。教程包含資源連結,而想法只是專案的一般描述。我還列出了我最喜歡的初學者清單。 看看,看看是否有什麼啟發你! 教學 == 我的最愛 ---- - [透過 30 個教學在 30 天內建立 30 個東西](https://javascript30.com) - [在 30 分鐘內建立一個簡單的搜尋機器人](https://medium.freecodecamp.org/how-to-build-a-simple-search-bot-in-30-minutes-eb56fcedcdb1) - [使用 Xamarin 和 Visual Studio 建立 iOS 照片庫應用程式](https://www.raywenderlich.com/134049/building-ios-apps-with-xamarin-and-visual-studio) - [建立 Android 手電筒應用程式](https://www.youtube.com/watch?v=dhWL4DC7Krs)(影片) - [製作聊天應用程式](https://medium.freecodecamp.org/how-to-build-a-chat-application-using-react-redux-redux-saga-and-web-sockets-47423e4bc21a) - [使用 React Native 建立 ToDo 應用程式](https://blog.hasura.io/tutorial-fullstack-react-native-with-graphql-and-authentication-18183d13373a) 簡單的 --- - [使用 C# 和 Xamarin 建立空白應用程式(正在進行中)](https://www.intertech.com/Blog/xamarin-tutorial-part-1-create-a-blank-app/) - [使用 Xamarin 和 Visual Studio 建立 iOS 照片庫應用程式](https://www.raywenderlich.com/134049/building-ios-apps-with-xamarin-and-visual-studio) - [建立加載畫面](https://medium.freecodecamp.org/how-to-build-a-delightful-loading-screen-in-5-minutes-847991da509f) - [使用 JS 建立 HTML 計算器](https://medium.freecodecamp.org/how-to-build-an-html-calculator-app-from-scratch-using-javascript-4454b8714b98) - [建立 React Native Todo 應用程式](https://egghead.io/courses/build-a-react-native-todo-application) - 使用 Node.js 編寫 Twitter 機器人 ``` - [Part 1](https://codeburst.io/build-a-simple-twitter-bot-with-node-js-in-just-38-lines-of-code-ed92db9eb078) ``` ``` - [Part 2](https://codeburst.io/build-a-simple-twitter-bot-with-node-js-part-2-do-more-2ef1e039715d) ``` - [建立一個簡單的 RESTFUL Web 應用程式](https://closebrace.com/tutorials/2017-03-02/creating-a-simple-restful-web-app-with-nodejs-express-and-mongodb) - [在 30 分鐘內建立一個簡單的搜尋機器人](https://medium.freecodecamp.org/how-to-build-a-simple-search-bot-in-30-minutes-eb56fcedcdb1) - [建立一個工作抓取 Web 應用程式](https://medium.freecodecamp.org/how-i-built-a-job-scraping-web-app-using-node-js-and-indreed-7fbba124bbdc) - [使用 Python 挖掘 Twitter 資料](https://marcobonzanini.com/2015/03/02/mining-twitter-data-with-python-part-1/) - [使用 Scrapy 和 MongoDB 抓取網站](https://realpython.com/blog/python/web-scraping-with-scrapy-and-mongodb/) - [如何使用 Python 和 Selenium WebDriver 進行抓取](http://www.byperth.com/2018/04/25/guide-web-scraping-101-what-you-need-to-know-and-how-to-scrape-with-python-selenium-webdriver/) - [我應該使用 BeautifulSoup 觀看哪部電影](https://medium.com/@nishantsahoo.in/which-movie-should-i-watch-5c83a3c0f5b1) - [使用 Flask 建立微博](https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world) - 在 Django 中建立部落格 Web 應用程式 ``` - [Part I : Introduction](https://tutorial.djangogirls.org/en/) ``` ``` - [Part II : Extension To Add More Features](https://legacy.gitbook.com/book/djangogirls/django-girls-tutorial-extensions/details) ``` - [選擇您自己的冒險演示](https://www.twilio.com/blog/2015/03/choose-your-own-adventures-presentations-wizard-mode-part-1-of-3.html) - [使用 Flask 和 RethinkDB 建立待辦事項列表](https://realpython.com/blog/python/rethink-flask-a-simple-todo-list-powered-by-flask-and-rethinkdb/) 中等的 --- - [透過建立簡單的 RPG 遊戲來學習 C#](http://scottlilly.com/learn-c-by-building-a-simple-rpg-index/) - [用 C# 創作 Rogue-like 遊戲](https://roguesharp.wordpress.com/) - [使用 Clojure 建構 Twitter 機器人](http://howistart.org/posts/clojure/1/index.html) - [建立拼字檢查器](https://bernhardwenzel.com/articles/clojure-spellchecker/) - [使用 Java 建立簡單的 HTTP 伺服器](http://javarevisited.blogspot.com/2015/06/how-to-create-http-server-in-java-serversocket-example.html) - [建立 Android 手電筒應用程式](https://www.youtube.com/watch?v=dhWL4DC7Krs)(影片) - [建立具有使用者身份驗證的 Spring Boot 應用程式](https://scotch.io/tutorials/build-a-spring-boot-app-with-user-authentication) - [透過 30 個教學在 30 天內建立 30 個東西](https://javascript30.com) - [使用純 JS 建立應用程式](https://medium.com/codingthesmartway-com-blog/pure-javascript-building-a-real-world-application-from-scratch-5213591cfcd6) - [建立無伺服器 React.js 應用程式](http://serverless-stack.com/) - [建立 Trello 克隆](http://codeloveandboards.com/blog/2016/01/04/trello-tribute-with-phoenix-and-react-pt-1/) - [使用 React、Node、MongoDB 和 SocketIO 建立角色投票應用程式](http://sahatyalkabov.com/create-a-character-voting-app-using-react-nodejs-mongodb-and-socketio/) - [React 教學:克隆 Yelp](https://www.fullstackreact.com/articles/react-tutorial-cloning-yelp/) - [使用 React.js 和 Node.js 建立簡單的中型克隆](https://codeburst.io/build-simple-medium-com-on-node-js-and-react-js-a278c5192f47) - [在 JS 中整合 MailChimp](https://medium.freecodecamp.org/how-to-integrate-mailchimp-in-a-javascript-web-app-2a889fb43f6f) - [使用 React Native 建立 ToDo 應用程式](https://blog.hasura.io/tutorial-fullstack-react-native-with-graphql-and-authentication-18183d13373a) - [製作聊天應用程式](https://medium.freecodecamp.org/how-to-build-a-chat-application-using-react-redux-redux-saga-and-web-sockets-47423e4bc21a) - [使用 React Native 建立新聞應用程式](https://medium.freecodecamp.org/create-a-news-app-using-react-native-ced249263627) - [學習 React 的 Webpack](https://medium.freecodecamp.org/learn-webpack-for-react-a36d4cac5060) - [建立您自己的 React 樣板](https://medium.freecodecamp.org/how-to-build-your-own-react-boilerplate-2f8cbbeb9b3f) - [基本 React+Redux 入門教學](https://hackernoon.com/a-basic-react-redux-introductory-tutorial-adcc681eeb5e) - [建立一個預約安排程序](https://hackernoon.com/build-an-appointment-scheduler-using-react-twilio-and-cosmic-js-95377f6d1040) - 使用 Angular 2+ 建立具有離線功能的 Hacker News 用戶端 ``` - [Part 1](https://houssein.me/angular2-hacker-news) ``` ``` - [Part 2](https://houssein.me/progressive-angular-applications) ``` - 帶有 Angular 5 的 ToDo 應用程式 ``` - [Introduction to Angular](http://www.discoversdk.com/blog/intro-to-angular-and-the-evolution-of-the-web) ``` ``` - [Part 1](http://www.discoversdk.com/blog/angular-5-to-do-list-app-part-1) ``` - 帶有 Angular 5 的 ToDo 應用程式 ``` - [Introduction to Angular](http://www.discoversdk.com/blog/intro-to-angular-and-the-evolution-of-the-web) ``` ``` - [Part 1](http://www.discoversdk.com/blog/angular-5-to-do-list-app-part-1) ``` 難的 -- - [建構一個解釋器](http://www.craftinginterpreters.com/)(第 14 章是用 C 寫的) - [用 C 語言寫一個 Shell](https://brennan.io/2015/01/16/write-a-shell-in-c/) - [編寫 FUSE 文件系統](https://www.cs.nmsu.edu/~pfeiffer/fuse-tutorial/) - [建立您自己的文字編輯器](http://viewsourcecode.org/snaptoken/kilo/) - [建立自己的 Lisp](http://www.buildyourownlisp.com/) - [建構 CoreWiki](https://www.youtube.com/playlist?list=PLVMqA0_8O85yC78I4Xj7z48ES48IQBa7p)這是一個 Wiki 風格的內容管理系統,完全用 C# 使用 ASP.NET Core 和 Razor Pages 編寫。您可以[在這裡](https://github.com/csharpfritz/CoreWiki)找到原始程式碼。 - [建構 JIRA 與 Clojure 和 Atlassian Connect 的集成](https://hackernoon.com/building-a-jira-integration-with-clojure-atlassian-connect-506ebd112807) - [建構一個解釋器](http://www.craftinginterpreters.com/)(第 4-13 章是用 Java 寫的) - [使用 Mocha、React、Redux 和 Immutable 透過測試優先開發來建立全端電影投票應用程式](https://teropa.info/blog/2015/09/10/full-stack-redux-tutorial.html) - [使用 React 和 Node 建立 Twitter Stream](https://scotch.io/tutorials/build-a-real-time-twitter-stream-with-node-and-react-js) - 使用 Webtask.io 建立無伺服器 MERN Story 應用程式 ``` - [Part 1](https://scotch.io/tutorials/build-a-serverless-mern-story-app-with-webtask-io-zero-to-deploy-1) ``` ``` - [Part 2](https://scotch.io/tutorials/build-a-serverless-mern-story-app-with-webtask-io-zero-to-deploy-2) ``` - [使用 React + Parcel 建立 Chrome 擴充功能](https://medium.freecodecamp.org/building-chrome-extensions-in-react-parcel-79d0240dd58f) ``` [Testing React App With Pupepeteer and Jest](https://blog.bitsrc.io/testing-your-react-app-with-puppeteer-and-jest-c72b3dfcde59) ``` - [用 React 編寫生命遊戲](https://medium.freecodecamp.org/create-gameoflife-with-react-in-one-hour-8e686a410174) - [建立帶有情感分析的聊天應用程式](https://codeburst.io/build-a-chat-app-with-sentiment-analysis-using-next-js-c43ebf3ea643) - [建立全端 Web 應用程式設置](https://hackernoon.com/full-stack-web-application-using-react-node-js-express-and-webpack-97dbd5b9d708) - 建立隨機報價機 ``` - [Part 1](https://www.youtube.com/watch?v=3QngsWA9IEE) ``` ``` - [Part 2](https://www.youtube.com/watch?v=XnoTmO06OYo) ``` ``` - [Part 3](https://www.youtube.com/watch?v=us51Jne67_I) ``` ``` - [Part 4](https://www.youtube.com/watch?v=iZx7hqHb5MU) ``` ``` - [Part 5](https://www.youtube.com/watch?v=lpba9vBqXl0) ``` ``` - [Part 6](https://www.youtube.com/watch?v=Jvp8j6zrFHE) ``` ``` - [Part 7](https://www.youtube.com/watch?v=M_hFfrN8_PQ) ``` - 使用 Angular 6 建立美麗的現實世界應用程式: ``` - [Part I](https://medium.com/@hamedbaatour/build-a-real-world-beautiful-web-app-with-angular-6-a-to-z-ultimate-guide-2018-part-i-e121dd1d55e) ``` - [使用 BootStrap 4 和 Angular 6 建立響應式佈局](https://medium.com/@tomastrajan/how-to-build-responsive-layouts-with-bootstrap-4-and-angular-6-cfbb108d797b) - [使用 Django 和測試驅動開發建立待辦事項列表](http://www.obeythetestinggoat.com/) - [使用 Python 建立 RESTful 微服務](http://www.skybert.net/python/developing-a-restful-micro-service-in-python/) - [使用 Docker、Flask 和 React 的微服務](https://testdriven.io/) - [使用 Flask 建立簡單的 Web 應用程式](https://pythonspot.com/flask-web-app-with-python/) - [使用 Flask 建立 RESTful API – TDD 方式](https://scotch.io/tutorials/build-a-restful-api-with-flask-the-tdd-way) - [在 20 分鐘內建立 Django API](https://codeburst.io/create-a-django-api-in-under-20-minutes-2a082a60f6f3) 想法 == 簡單的 --- ### 99 瓶 - 建立一個程序,列印歌曲“牆上的 99 瓶啤酒”的每一行。 - 不要使用所有數字的列表,也不要手動輸入所有數字。請改用內建函數。 - 除了短語“取下一個”之外,您不得直接在歌詞中輸入任何數字/數字名稱。 - 請記住,當您還剩下 1 瓶時,「瓶子」一詞將變為單數。 ### 魔術8球 - 模擬神奇的 8 球。 - 允許使用者輸入他們的問題。 - 顯示正在進行的訊息(即“思考”)。 - 建立 20 個回應,並顯示隨機回應。 - 允許用戶提出另一個問題或退出。 - 獎金: ``` - Add a gui. ``` ``` - It must have a box for users to enter the question. ``` ``` - It must have at least 4 buttons: ``` ``` - ask ``` ``` - clear (the text box) ``` ``` - play again ``` ``` - quit (this must close the window) ``` ### 石頭剪刀布遊戲 - 建立一個石頭剪刀布遊戲。 - 讓玩家選擇石頭、剪刀或布。 - 讓計算機選擇它的移動方式。 - 比較選擇並決定誰獲勝。 - 列印結果。 - 子目標: ``` - Give the player the option to play again. ``` ``` - Keep a record of the score (e.g. Player: 3 / Computer: 6). ``` ### 倒數時鐘 - 建立一個程序,允許使用者選擇時間和日期,然後以給定的時間間隔(例如每秒)列印一條訊息,告訴使用者距離所選時間還有多長時間。 - 子目標: ``` - If the selected time has already passed, have the program tell the user to start over. ``` ``` - If your program asks for the year, month, day, hour, etc. separately, allow the user to be able to type in either the month name or its number. ``` ``` - TIP: Making use of built in modules such as time and datetime can change this project from a nightmare into a much simpler task. ``` 中等的 --- ### 番茄計時器 建立一個番茄計時器。 番茄計時器是一種時間管理方法。該技術使用計時器將工作分解為多個時間間隔,通常長度為 25 分鐘,中間間隔短暫的休息。這些間隔被命名為“pomodoros”,是意大利語單字“pomodoro”(番茄)的英文複數形式,以西里洛在大學時使用的番茄形狀的廚房計時器命名。 原始技巧有六個步驟: 決定要完成的任務。 設定番茄計時器(傳統上為 25 分鐘)。 完成任務。 當計時器響起時結束工作並在一張紙上畫上複選標記。 如果您的複選標記少於四個,請短暫休息(3-5 分鐘),然後轉到步驟 2。 四個番茄鐘後,休息較長時間(15-30 分鐘),將複選標記計數重設為零,然後轉到步驟 1。 要了解有關番茄計時器的更多訊息[,請單擊此處](https://en.wikipedia.org/wiki/Pomodoro_Technique) ### 谷歌案例 - 這是一個可以讓你玩英文句子的遊戲。 - 使用者將以任何格式輸入一個句子。(大寫或小寫或兩者的混合) - 程式必須將給定的句子轉換為Google大小寫。什麼是Google大小寫句子風格?\[know\_about\_it\_here:\](這是一種寫作風格,我們將所有小寫字母替換為大寫字母,留下所有單字的首字母)。 - 子目標: ``` - Program must then convert the given sentence in camel case.To know more about camel case ``` ``` [click_here](https://en.wikipedia.org/wiki/Camel_case) ``` ``` - Sentence can be entered with any number of spaces. ``` ### 擲骰子模擬器 - 允許使用者輸入骰子的面數以及應擲骰子的次數。 - 您的程式應該模擬擲骰子並追蹤每個數字出現的次數(這不必顯示)。 - 最後,列印出每個數字出現的次數。 - 子目標: ``` - Adjust your program so that if the user does not type in a number when they need to, the program will keep prompting them to type in a real number until they do so. ``` ``` - Put the program into a loop so that the user can continue to simulate dice rolls without having to restart the entire program. ``` ``` - In addition to printing out how many times each side appeared, also print out the percentage it appeared. If you can, round the percentage to 4 digits total OR two decimal places. ``` - 獎金: ``` - You are about to play a board game, but you realize you don't have any dice. Fortunately you have this program. ``` ``` - 1. Create a program that opens a new window and draws 2 six-sided dice ``` ``` - 2. Allow the user to quit, or roll again ``` ``` - Allow the user to select the number of dice to be drawn on screen(1-4) 2. Add up the total of the dice and display it ``` ### 計算並修復綠雞蛋和火腿 你們有些人可能還記得蘇博士的故事「綠雞蛋和火腿」。對於那些不記得或從未聽說過的人,[這](http://pastebin.com/XMY48CnN)是這個故事。然而,我給你的故事有一個問題——每次使用「我」這個詞時,它都是小寫的。 由於此問題,您的工作是執行以下操作: - 將我給您的故事複製到常規文字檔案中。 - 建立一個程式來通讀故事並在任何時候將字母 i 變為大寫。 (當它也用在 sam-I-am 的名字中時,請務必更改它。) - 讓你的程式建立一個新文件,並讓它正確地寫出故事。 - 印出有多少錯誤被修正。 - 完成後,您應該已經糾正了[這麼多](https://i.imgur.com/GRkj3yz.jpg)錯誤。 難的 -- ### 隨機維基百科文章 如果您曾造訪維基百科,您可能已經注意到螢幕左側有一個指向隨機文章的連結。雖然看到您被帶到哪篇文章可能很有趣,但有時看到文章的名稱會很好,這樣您就可以在聽起來很無聊時跳過它。幸運的是,維基百科有一個 API,允許我們這樣做[點擊這裡](https://en.wikipedia.org/w/api.php?action=query&list=random&rnnamespace=0&rnlimit=10&format=json)。 然而,有一個困境。由於維基百科擁有有關世界各地主題的文章,其中一些文章的標題中包含特殊字元。例如,關於西班牙畫家[埃拉斯托·科爾特斯·華雷斯 (Erasto Cortés Juárez)](https://en.wikipedia.org/wiki/Erasto_Cort%C3%A9s_Ju%C3%A1rez)的文章中就有 é 和 á。如果您查看這篇特定文章的[API](https://en.wikipedia.org/w/api.php?action=query&prop=info&pageids=39608394&inprop=url&format=json) ,您將看到標題是“Erasto Cort\\u00e9s Ju\\u00e1rez”,並且 \\u00e9 和 \\u00e1 正在替換前面提到的兩個字母。 (有關這是什麼的訊息,請首先查看文件中[本頁](https://docs.python.org/2/howto/unicode.html)的前半部分)。為了讓你的程式正常運作,你必須以某種方式處理這個問題。 - 建立一個程序,從官方維基百科 API 中提取標題,然後一一詢問用戶是否願意閱讀該文章。 - 例子: ``` - If the first title is Reddit, then the program should ask something along the lines of "Would you like to read about Reddit?" If the user says yes, then the program should open up the article for the user to read. ``` ``` - HINT: Click [here](https://en.wikipedia.org/wiki?curid=39608394) to see how the article's ID can be used to access the actual article. ``` - 子目標: ``` - As mentioned before, do something about the possibility of unicode appearing in the title. ``` ``` - Whether you want your program to simply filter out these articles or you want to actually turn the codes into readable characters, that's up to you. ``` ``` - Make the program pause once the user has selected an article to read, and allow him or her to continue browsing different article titles once finished reading. ``` ``` - Allow the user to simply press ENTER to be asked about a new article. ``` ### 天氣如何? 如果您想了解 API 的基礎知識,請查看 iamapizza 的[這篇](http://www.reddit.com/r/explainlikeimfive/comments/qowts/eli5_what_is_api/c3z9kok)文章。 - 建立一個程序,從 OpenWeatherMap.org 提取資料並列印有關當前天氣的訊息,例如您居住的地方的最高氣溫、最低氣溫和雨量。 - 子目標: ``` - Print out data for the next 5-7 days so you have a 5 day/week long forecast. ``` ``` - Print the data to another file that you can open up and view at, instead of viewing the information in the command line. ``` ``` - If you know html, write a file that you can print information to so that your project is more interesting. ``` - 尖端: ``` - APIs that are in Json are essentially lists and dictionaries. Remember that to reference something in a list, you must refer to it by what number element it is in the list, and to reference a key in a dictionary, you must refer to it by its name. ``` ``` - Don't like Celsius? Add &units=imperial to the end of the URL of the API to receive your data in Fahrenheit. ``` ### 來源 - https://github.com/tuvtran/project-based-learning - https://github.com/jorgegonzalez/beginner-projects - https://github.com/MunGell/awesome-for-beginners/blob/master/README.md - https://github.com/sarahbohr/AbsoluteBeginnerProjects --- 你怎麼認為?您喜歡透過特定專案進行學習還是不喜歡透過特定專案進行學習? --- 原文出處:https://dev.to/samborick/100-project-ideas-oda

您付費工具的開源替代品

**開源吞噬軟體** 我建立了 [osssoftware.org](http://osssoftware.org),重點是: - PH 獲獎者 - DevHunt 上最好的開發工具 - 最近在 GitHub 上活躍 - 大多數網路反向連結 - 大多數被提及為“替代......” 👇 **301 個開源替代方案:** - [Supabase](http://supabase.com) - Firebase 的開源替代品 - [Documenso](http://documenso.com) - Docusign 的開源替代方案 - [Cal](http://cal.com) - Calendly 的替代品 - [Plausible](http://plausible.io) - Google Analytics 的開源替代品 - [DevHunt](http://devhunt.org) - ProductHunt 的開源替代品 - [AI.Meta](http://ai.meta.com/llama) - ChatGPT 的開源替代品 - [Papermark](http://papermark.io) - Docsend 的開源替代品 - [Godot Engine](http://godotengine.org) - Unity3D 的開源替代品 - [Ghost](http://ghost.org) - Medium 的開源替代方案 - [Mastodon](http://joinmastodon.org) - Twitter 的開源替代品 - [Rowy](http://rowy.io) - Airtable 的開源替代品 - [Sentry](http://sentry.io) - 錯誤追蹤的開源替代方案 - [N8N](http://n8n.io) - Zapier 的開源替代品 - [Appsmith](http://appsmith.com) - Retool 的開源替代方案 - [ClickHouse](http://clickhouse.com) - BigQuery 的開源替代品 - [GitLab](http://gitlab.com) - GitHub 的開源替代品 - [Penpot](http://penpot.app) - Figma 的開源替代品 - [Jenkins](http://jenkins.io) - DevOps 的開源替代方案 - [Forem](http://forem.com) - Circle 的開源替代品 - [PostHog](http://posthog.com) - Mixpanel 的開源替代品 - [Dub](http://dub.co) - Bitly 的開源替代方案 - [OpenCart](http://opencart.com) - Shopify 的開源替代品 - [類型](http://typesense.org) - Algolia 的開源替代品 - [AppFlowy](http://appflowy.io) - Notion 的開源替代品 - [Webstudio](http://webstudio.is) - Webflow 的開源替代方案 - [Typebot](http://typebot.io) - Typeform 的開源替代品 - [Passbolt](http://passbolt.com) - 1Password 的開源替代品 - shadcn - Tailwind UI 的開源替代方案 **看更多:** - [所有開源替代品](http://osssoftware.org/open-source-alternatives/) - [類別](http://osssoftware.org) **貢獻:** 如果您認為應該加入一個很棒的工具,請在網站上提交它或給我發送 DM 或回复此帖子。 我的推特 [@johnrushx](https://twitter.com/johnrushx) 順便說一句,我們正在進行 Product Hunt 感謝您的支持 →→→ [producthunt.com/osssoftware](https://www.producthunt.com/posts/opensource-alternatives-to-tools-you-pay) --- 原文出處:https://dev.to/johnrushx/open-source-alternatives-to-tools-you-pay-for-1g9c

✨23 個開源函式庫,用於將您的作品集發射到月球🚀🚀

為優秀的開源庫做出貢獻是建立作品集的好方法。 我已經編譯了 23 個優秀的開源程式庫和一些很好的入門問題。 不要忘記加星號並支持這些🌟 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fi3dd111pv2948ya21w2.gif) --- #產品中的人工智慧: ### 1. [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 應用內 AI 聊天機器人與 AI 文字區域 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ox3mv8nmqzot6m4kvkdh.png) 開源平台,用於使用兩個 React 元件將關鍵 AI 功能整合到 React 應用程式中。 CopilotPortal:應用程式內人工智慧聊天機器人,可以「查看」當前應用程式狀態並採取行動。 CopilotTextarea:AI 驅動的 <textarea /'> 替換。具有自動完成、插入和生成功能。 ###[好第一期:](https://github.com/CopilotKit/CopilotKit/issues/62) ``` Support bold and italicized text in CopilotTextarea Proposal: Add support for bold and italicized text in CopilotTextarea CopilotTextarea uses slate-js under the hood. Lots of examples for adding bold/italicized support Initially only add programatic support. UI support will be added separately in [TODO add issue] Implementation tips: changes will be made to render-element.tsx and base-copilot-textarea.tsx custom-editor.tsx structures may also require changes ``` {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} --- ###2.[Tavily GPT 研究員](https://github.com/assafelovic/gpt-researcher){% embed https://github.com/assafelovic/gpt-researcher no-readme %} ###3.[Pezzo.ai](https://github.com/pezzolabs/pezzo){% 嵌入 https://github.com/pezzolabs/pezzo no-readme %} ###4.[Weaviate](https://github.com/weaviate/weaviate){% 嵌入 https://github.com/weaviate/weaviate no-readme %} ###5.[LangChain](https://github.com/langchain-ai/langchain){% 嵌入 https://github.com/langchain-ai/langchain no-readme %} --- &nbsp; #🛜網頁開發: ### 6. [Wasp](https://github.com/wasp-lang/wasp) - 使用 React 和 Node.js 開發全端 Web 應用程式 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/54jp6j6r8ils6we97i0f.png) 使用 React 和 Node.js 進行快速全端 Web 應用程式開發。 Wasp 提供了一種建立現代 Web 應用程式的簡化方法,將前端的 React 和後端的 Node.js 結合在一個緊密結合的框架中。 ###[好第一期:](https://github.com/wasp-lang/wasp/issues/874) ``` Add images (or link to the example app) of auth UI helpers Wasp provides At this point in docs (also in the tutorial if we're using it), it would be nice to add an image of UI helpers for Auth (login/signup form, Google/GitHub button, ...) so developers can immediately see what they are getting and how nice it looks. ``` {% cta https://github.com/wasp-lang/wasp %} 星黃蜂 ⭐️ {% endcta %} --- ###7.[ClickVote](https://github.com/clickvote/clickvote) {% 嵌入 https://github.com/clickvote/clickvote no-readme %} ###8.[ReactFlow](https://github.com/xyflow/xyflow) {% 嵌入 https://github.com/xyflow/xyflow no-readme %} ###9.[Trigger.dev](https://github.com/triggerdotdev/trigger.dev) {% 嵌入 https://github.com/triggerdotdev/trigger.dev no-readme %} ###10.[Novu](https://github.com/novuhq/novu) {% 嵌入 https://github.com/novuhq/novu no-readme %} --- &nbsp; #🧑‍💻DevOps: ### 11. [Logstash](https://github.com/elastic/logstash) - 由 elastic 傳輸和處理日誌和事件。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0nhya28nmwby9lurtrta.png) 輕鬆將點讚、按讚和評論加入到您的網路應用程式中。 用於加入這些元件的簡單反應程式碼。 ### [第一期好](https://github.com/elastic/logstash/issues/15561) ``` Allow comments in pipeline config between hash entries Currently it seems not allowed to make comments between hash entries, this is a feature request to allow it. ``` {% cta https://github.com/elastic/logstash %} 明星 Logstash ⭐️ {% endcta %} --- ###12.[Odigos](https://github.com/keyval-dev/odigos) {% 嵌入 https://github.com/keyval-dev/odigos no-readme %} ###13.[Glasskube](https://github.com/glasskube/operator) {% 嵌入 https://github.com/glasskube/operator no-readme %} ###14.[鏡像](https://github.com/metalbear-co/mirrord){% 嵌入 https://github.com/metalbear-co/mirrord no-readme %} ###15.[挖土機](https://github.com/diggerhq/digger) {% 嵌入 https://github.com/diggerhq/digger no-readme %} --- &nbsp; #💽資料庫: ### 16. [Supabase](https://github.com/supabase/supabase) - 開源 Rirebase 替代品 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j4xnzrefrjaaywu4b49p.png) 使用託管 Postgres、身份驗證和即時功能建立現代資料驅動應用程式 ###[第一期好:](https://github.com/supabase/supabase/issues/19396) ``` Horizontal Scroll for CodeBlocks Currently when reading the dcs, it's not possible to view all of the code for alot of the samples. Is this the Component rendered across all of the web properties, if so I'll be happy to throw on a horizontal scroll bar that matches supabase branding. ``` {% cta https://github.com/supabase/supabase %} 明星 Supabase ⭐️ {% endcta %} --- ###17.[Appwrite](https://github.com/appwrite/appwrite){% 嵌入 https://github.com/appwrite/appwrite no-readme %} ###18.[Superduperdb] (https://github.com/SuperDuperDB/superduperdb){% 嵌入 https://github.com/SuperDuperDB/superduperdb no-readme %} ###19.[Milvus](https://github.com/milvus-io/milvus) {% 嵌入 https://github.com/milvus-io/milvus no-readme %} --- &nbsp; #👾其他: ### 21. [Snapify](https://github.com/MarconLP/snapify) - 開源螢幕錄製 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/89h8mjriix6hdihcrfr8.png) 螢幕錄製,但免費、開源,您負責自己的資料。 ###[好第一期:](https://github.com/MarconLP/snapify/issues/18) ``` Ability to create GIFs and take screenshots to also store in S3 ``` {% cta https://github.com/MarconLP/snapify %} 明星 Snapify ⭐️ {% endcta %} --- ###22.[ReactAgent](https://github.com/eylonmiz/react-agent){% 嵌入 https://github.com/eylonmiz/react-agent no-readme %} ###23.[對初學者來說很棒](https://github.com/MunGell/awesome-for-beginners){% embed https://github.com/MunGell/awesome-for-beginners no -readme %} --- #就是這樣,夥計們! ## 別忘了按讚、留言和收藏🫡 --- 原文出處:https://dev.to/copilotkit/23-open-source-libraries-to-launch-your-portfolio-to-the-moon-fe

🏆Pythonista 必備的 10 個 VSCode 擴展

## **TL;博士** 對於使用 VSCode 的 Python 開發人員、資料科學家和分析師來說,此編譯提供了一些擴展,可以提高 Python 和一般編碼需求的編碼生產力和效率。 ![介紹 GIF](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lhcge6eywoumtc7hyuxr.gif) <小時/> ## 1. [Taipy Studio](https://marketplace.visualstudio.com/items?itemName=Taipy.taipy-studio) Taipy 是一個開源 Python 庫,用於建立 Web 應用程式前端和後端。 您只需使用 Python 即可為您的資料/機器學習用例建立多頁面、多用戶和可自訂的 GUI。 但它不止於此。 Taipy 還可以處理您的後端,因為它允許管道編排和管理。 現在,回到 Taipy Studio 的 VSCode 擴充功能。此擴充功能是兩個工具的包裝器,旨在加速 Taipy 應用程式的建立。 - Taipy Studio Configuration Builder:圖形管道編輯器,全部在點擊環境中; - Taipy Studio GUI 助手:在編寫 GUI 時包括 IntelliSense。 ![太比 PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7bju9pbjeaap2tditivf.png) <小時/> ![QueenB](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ovcc5kqd8xr9uihrggbb.gif) {% cta https://github.com/Avaiga/taipy %} Star ⭐ Taipy 儲存庫 {% endcta %} 我們已經快有 2000 顆星了,沒有你我們無法做到這一點🙏 <小時/> ## 2. [Github Copilot](https://marketplace.visualstudio.com/items?itemName=GitHub.copilot) 還需要出示副駕駛嗎?這個工具就是您自己的程式碼助手。 利用人工智慧,Copilot 可以無縫地自動完成您的程式碼。 另一個主要功能是能夠提供上下文感知建議。 對於開發人員來說,這是一個偉大的遊戲規則改變者,可以節省時間和提高效率,並且將其直接作為 VSCode 擴展使用是完全有意義的。 ![副駕駛 PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6192xn9g47gn2693r4j2.png) <小時/> ## 3. [Rainbow CSV](https://marketplace.visualstudio.com/items?itemName=mechatroner.rainbow-csv) 光看名字,你就差不多能猜到這個工具的功能了。 Rainbow CSV 將透過以不同顏色突出顯示列來讓您的 CSV 檔案易於閱讀。 就這麼簡單,但對任何處理資料的人來說都很有幫助。真正改變使用者視覺體驗的遊戲規則。 ![RCSV PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tdvs5fyi12tprdc3gch4.png) <小時/> ## 4. [待辦事項樹](https://marketplace.visualstudio.com/items?itemName=Gruntfuggly.todo-tree) 對於需要在程式碼的待辦事項清單中進行組織的人來說,這個工具非常有用。使用此擴展,只需在需要時在程式碼中加入 TODO 或 FIXME 標記即可。 ToDo Tree 將會尋找這些標籤並將它們組織成樹狀結構。 現在您可以輕鬆返回標籤。 ![TODO 樹 PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/csiyv0rnp81lod36ksw7.png) <小時/> ## 5. [Jupyter](https://marketplace.visualstudio.com/items?itemName=ms-toolsai.jupyter) 如果您想使用類似筆記本的 IDE 來啟動資料/ML 專案以促進探索和實驗,VSCode 透過 Jupyter 擴充功能提供此功能。 當筆記型電腦的限制(例如擴展、部署、測試和維護)使得有必要轉向更傳統的編碼實踐時,在 VSCode 上進行所有設定只會讓事情變得更容易。 ![Jupyter PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dbw6rqi4y2sls2466r02.png) <小時/> ## 6. [Markdown 表情符號](https://marketplace.visualstudio.com/items?itemName=bierner.markdown-emoji) 這裡並沒有什麼真正令人驚訝的地方。此 VSCode 擴展為 VSCode Markdown 預覽提供表情符號支持,這是為任何 Markdown 專案加入表現和可讀性的好方法。 ![MKD 表情符號 PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7oaj92h9s95e2mtt0vr0.png) <小時/> ## 7. [Pylint](https://marketplace.visualstudio.com/items?itemName=ms-python.pylint) Pylint 與 Python linter 同名,是其在 VSCode 中的擴充。它透過分析程式碼、檢查錯誤並為您提供改進建議來幫助您提高效率。 確保您的腳本遵循所有編碼標準是必須的。 ![Pylint GIF](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lv6mcilflhupaultx160.gif) <小時/> ## 8. [Pylance](https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance) Pylance 是 Python 語言的支援。 它最初作為 Python 庫存在,但透過此擴充整合到 VSCode 中。 一些主要特點: - 程式碼完成 - 自動導入 - 與 Juypter 筆記本相容 - 語意突出顯示 ![皮蘭斯 PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s04exzm5y61m6rwjvhru.png) <小時/> ## 9. [Liveshare](https://marketplace.visualstudio.com/items?itemName=MS-vsliveshare.vsliveshare) 使用此 VSCode 擴充功能可以輕鬆進行協作。無需配置任何東西;只需啟動 Liveshare 會話並繼續除錯會話即可。 Liveshare 也保留您所有的個人 IDE 首選項,讓協作更加輕鬆。 ![Liveshare PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0the1beedaze59z7qcl.png) <小時/> ## 10. [Markdown 多合一](https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one) 此擴充增強了 VSCode 中 Markdown 的使用,並具有各種不同的功能: - 內容表生成 - 鍵盤快速鍵 - 程式碼區塊插入 - 預覽功能 該工具非常適合編寫“README.md”檔案。 ![MD AIO PNG](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2yji1wmk9lvp9plqp631.png) <小時/> 由於各種原因,VSCode 已成為開發人員最常使用的 IDE 之一。 它的主要功能包括強大的 git 整合和跨平台支持,但擴展是一個突出的功能。 它們支援自訂您的環境,促進與各種工具的無縫整合。 <小時/> 希望您喜歡這篇文章! 我是一名新手作家,歡迎任何改進建議! ![新秀圖片](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/25oebh36ha622u74kpli.gif) 如果您有任何疑問,請隨時與我們聯繫。 --- 原文出處:https://dev.to/taipy/top-10-must-have-vscode-extensions-forpythonistas-561a

🔥 大幅提升你的 NextJS 能力:嘗試手寫一個 GitHub 星星監視器 🤯

在本文中,您將學習如何建立 **GitHub 星數監視器** 來檢查您幾個月內的星數以及每天獲得的星數。 - 使用 GitHub API 取得目前每天收到的星星數量。 - 在螢幕上每天繪製美麗的星星圖表。 - 創造一個工作來每天收集新星星。 ![吉米](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n524rmr0gpgr79p4qlhj.gif) --- ## 你的後台工作平台🔌 [Trigger.dev](https://trigger.dev/) 是一個開源程式庫,可讓您使用 NextJS、Remix、Astro 等為您的應用程式建立和監控長時間執行的作業!   [![GiveUsStars](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bm9mrmovmn26izyik95z.gif)](https://github.com/triggerdotdev/trigger.dev) 請幫我們一顆星🥹。 這將幫助我們建立更多這樣的文章💖 https://github.com/triggerdotdev/trigger.dev --- ## 這是你需要知道的 😻 取得 GitHub 上星星數量的大部分工作將透過 GitHub API 完成。 GitHub API 有一些限制: - 每個請求最多 100 名觀星者 - 最多 100 個同時請求 - 每小時最多 60 個請求 [TriggerDev](https://github.com/triggerdotdev/trigger.dev) 儲存庫擁有超過 5000 顆星,實際上不可能在合理的時間內(即時)計算所有星數。 因此,我們將採用與 [GitHub Stars History](https://star-history.com/) 相同的技巧。 - 取得星星總數 (**5,715**) 除以每頁 **100** 結果 = **58 頁** - 設定我們想要的最大請求量(**20 頁最大**)除以 **58 頁** = 跳過 3 頁。 - 從這些頁面中獲取星星**(2000 顆星)**,然後獲取剩餘的星星,我們將按比例加入到其他日期(**3715 顆星**)。 它會為我們繪製一個漂亮的圖表,並在需要的地方用星星凸起。 當我們每天獲取新數量的星星時,事情就會變得容易得多。 我們將用目前擁有的星星總數減去 GitHub 上的新星星數量。 **我們不再需要迭代觀星者。** --- ## 讓我們來設定一下 🔥 我們的申請將包含一頁: - 新增您想要監控的儲存庫。 - 查看儲存庫清單及其 GitHub 星圖。 - 刪除那些你不再想要的。 ![StarsOverTime](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rbii15mn1tyuz63kjphk.png) > 💡 我們將使用 NextJS 新的應用程式路由器,在安裝專案之前請確保您的節點版本為 18+。 > 使用 NextJS 設定一個新專案 ``` npx create-next-app@latest ``` 我們必須將所有星星保存到我們的資料庫中! 在我們的示範中,我們將使用 SQLite 和 `Prisma`。 它非常容易安裝,但可以隨意使用任何其他資料庫。 ``` npm install prisma @prisma/client --save ``` 在我們的專案中安裝 Prisma ``` npx prisma init --datasource-provider sqlite ``` 轉到“prisma/schema.prisma”並將其替換為以下模式: ``` generator client { provider = "prisma-client-js" } datasource db { provider = "sqlite" url = env("DATABASE_URL") } model Repository { id String @id @default(uuid()) month Int year Int day Int name String stars Int @@unique([name, day, month, year]) } ``` 然後執行 ``` npx prisma db push ``` 我們基本上已經在 SQLite 資料庫中建立了一個名為「Repository」的新表: - 「月」、「年」、「日」是日期。 - `name` 儲存庫的名稱 - 「星星」以及該特定日期的星星數量。 你還可以看到我們在底部加入了一個`@@unique`,這意味著我們可以將`name`,`month`,`year`,`day`一起重複記錄。它會拋出一個錯誤。 讓我們新增 Prisma 客戶端。 建立一個名為「helper」的新資料夾,並新增一個名為「prisma.ts」的新文件,並在其中新增以下程式碼: ``` import {PrismaClient} from '@prisma/client'; export const prisma = new PrismaClient(); ``` 我們稍後可以使用該「prisma」變數來查詢我們的資料庫。 --- ## 應用程式 UI 骨架 💀 我們需要一些函式庫來完成本教學: - **Axios** - 向伺服器發送請求(如果您覺得更舒服,可以隨意使用 fetch) - **Dayjs -** 很棒的處理日期的函式庫。它是 moment.js 的替代品,但不再完全維護。 - **Lodash -** 很酷的資料結構庫。 - **react-hook-form -** 處理表單的最佳函式庫(驗證/值/等) - **chart.js** - 我選擇繪製 GitHub 星圖的函式庫。 讓我們安裝它們: ``` npm install axios dayjs lodash @types/lodash chart.js react-hook-form react-chartjs-2 --save ``` 建立一個名為“components”的新資料夾並新增一個名為“main.tsx”的新文件 新增以下程式碼: ``` "use client"; import {useForm} from "react-hook-form"; import axios from "axios"; import {Repository} from "@prisma/client"; import {useCallback, useState} from "react"; export default function Main() { const [repositoryState, setRepositoryState] = useState([]); const {register, handleSubmit} = useForm(); const submit = useCallback(async (data: any) => { const {data: repositoryResponse} = await axios.post('/api/repository', {todo: 'add', repository: data.name}); setRepositoryState([...repositoryState, ...repositoryResponse]); }, [repositoryState]) const deleteFromList = useCallback((val: List) => () => { axios.post('/api/repository', {todo: 'delete', repository: `https://github.com/${val.name}`}); setRepositoryState(repositoryState.filter(v => v.name !== val.name)); }, [repositoryState]) return ( <div className="w-full max-w-2xl mx-auto p-6 space-y-12"> <form className="flex items-center space-x-4" onSubmit={handleSubmit(submit)}> <input className="flex-grow p-3 border border-black/20 rounded-xl" placeholder="Add Git repository" type="text" {...register('name', {required: 'true'})} /> <button className="flex-shrink p-3 border border-black/20 rounded-xl" type="submit"> Add </button> </form> <div className="divide-y-2 divide-gray-300"> {repositoryState.map(val => ( <div key={val.name} className="space-y-4"> <div className="flex justify-between items-center py-10"> <h2 className="text-xl font-bold">{val.name}</h2> <button className="p-3 border border-black/20 rounded-xl bg-red-400" onClick={deleteFromList(val)}>Delete</button> </div> <div className="bg-white rounded-lg border p-10"> <div className="h-[300px]]"> {/* Charts Component */} </div> </div> </div> ))} </div> </div> ) } ``` **超簡單的React元件** - 允許我們新增新的 GitHub 庫並將其發送到伺服器 POST 的表單 - `/api/repository` `{todo: 'add'}` - 刪除我們不需要 POST 的儲存庫 - `/api/repository` `{todo: 'delete'}` - 所有新增的庫及其圖表的清單。 讓我們轉到本文的複雜部分,新增儲存庫。 --- ## 數星星 ![CountingStars](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4m2j6046myxwv2c8kwla.gif) 在「helper」內部建立一個名為「all.stars.ts」的新檔案並新增以下程式碼: ``` import axios from "axios"; import dayjs from "dayjs"; import utc from 'dayjs/plugin/utc'; dayjs.extend(utc); const requestAmount = 20; export const getAllGithubStars = async (owner: string, name: string) => { // Get the amount of stars from GitHub const totalStars = (await axios.get(`https://api.github.com/repos/${owner}/${name}`)).data.stargazers_count; // get total pages const totalPages = Math.ceil(totalStars / 100); // How many pages to skip? We don't want to spam requests const pageSkips = totalPages < requestAmount ? requestAmount : Math.ceil(totalPages / requestAmount); // Send all the requests at the same time const starsDates = (await Promise.all([...new Array(requestAmount)].map(async (_, index) => { const getPage = (index * pageSkips) || 1; return (await axios.get(`https://api.github.com/repos/${owner}/${name}/stargazers?per_page=100&page=${getPage}`, { headers: { Accept: "application/vnd.github.v3.star+json", }, })).data; }))).flatMap(p => p).reduce((acc: any, stars: any) => { const yearMonth = stars.starred_at.split('T')[0]; acc[yearMonth] = (acc[yearMonth] || 0) + 1; return acc; }, {}); // how many stars did we find from a total of `requestAmount` requests? const foundStars = Object.keys(starsDates).reduce((all, current) => all + starsDates[current], 0); // Find the earliest date const lowestMonthYear = Object.keys(starsDates).reduce((lowest, current) => { if (lowest.isAfter(dayjs.utc(current.split('T')[0]))) { return dayjs.utc(current.split('T')[0]); } return lowest; }, dayjs.utc()); // Count dates until today const splitDate = dayjs.utc().diff(lowestMonthYear, 'day') + 1; // Create an array with the amount of stars we didn't find const array = [...new Array(totalStars - foundStars)]; // Set the amount of value to add proportionally for each day let splitStars: any[][] = []; for (let i = splitDate; i > 0; i--) { splitStars.push(array.splice(0, Math.ceil(array.length / i))); } // Calculate the amount of stars for each day return [...new Array(splitDate)].map((_, index, arr) => { const yearMonthDay = lowestMonthYear.add(index, 'day').format('YYYY-MM-DD'); const value = starsDates[yearMonthDay] || 0; return { stars: value + splitStars[index].length, date: { month: +dayjs.utc(yearMonthDay).format('M'), year: +dayjs.utc(yearMonthDay).format('YYYY'), day: +dayjs.utc(yearMonthDay).format('D'), } }; }); } ``` 那麼這裡發生了什麼事: - `totalStars` - 我們計算圖書館擁有的星星總數。 - `totalPages` - 我們計算頁數 **(每頁 100 筆記錄)** - `pageSkips` - 由於我們最多需要 20 個請求,因此我們檢查每次必須跳過多少頁。 - `starsDates` - 我們填充每個日期的星星數量。 - `foundStars` - 由於我們跳過日期,我們需要計算實際找到的星星總數。 - `lowestMonthYear` - 尋找我們擁有的恆星的最早日期。 - `splitDate` - 最早的日期和今天之間有多少個日期? - `array` - 一個包含 `splitDate` 專案數量的空陣列。 - `splitStars` - 我們缺少的星星數量,需要按比例加入每個日期。 - 最終返回 - 新陣列包含自開始以來每天的星星數量。 所以,我們已經成功建立了一個每天可以給我們星星的函數。 我嘗試過這樣顯示,結果很混亂。 您可能想要顯示每個月的星星數量。 此外,您可能想要累積星星**而不是:** - 二月 - 300 顆星 - 三月 - 200 顆星 - 四月 - 400 顆星 **如果有這樣的就更好了:** - 二月 - 300 顆星 - 三月 - 500 顆星 - 四月 - 900 顆星 兩個選項都有效。 **這取決於你想展示什麼!** 因此,讓我們轉到 helper 資料夾並建立一個名為「get.list.ts」的新檔案。 這是文件的內容: ``` import {prisma} from "./prisma"; import {groupBy, sortBy} from "lodash"; import {Repository} from "@prisma/client"; function fixStars (arr: any[]): Array<{name: string, stars: number, month: number, year: number}> { return arr.map((current, index) => { return { ...current, stars: current.stars + arr.slice(index + 1, arr.length).reduce((acc, current) => acc + current.stars, 0), } }).reverse(); } export const getList = async (data?: Repository[]) => { const repo = data || await prisma.repository.findMany(); const uniqMonth = Object.values( groupBy( sortBy( Object.values( groupBy(repo, (p) => p.name + '-' + p.year + '-' + p.month)) .map(current => { const stars = current.reduce((acc, current) => acc + current.stars, 0); return { name: current[0].name, stars, month: current[0].month, year: current[0].year } }), [(p: any) => -p.year, (p: any) => -p.month] ),p => p.name) ); const fixMonthDesc = uniqMonth.map(p => fixStars(p)); return fixMonthDesc.map(p => ({ name: p[0].name, list: p })); } ``` 首先,它將所有按日的星星轉換為按月的星星。 稍後我們會累積每個月的星星數量。 這裡要注意的一件主要事情是 `data?: Repository[]` 是可選的。 我們制定了一個簡單的邏輯:如果我們不傳遞資料,它將為我們資料庫中的所有儲存庫傳遞資料。 如果我們傳遞資料,它只會對其起作用。 為什麼問? - 當我們建立一個新的儲存庫時,我們需要在將其新增至資料庫後處理特定的儲存庫資料。 - 當我們重新載入頁面時,我們需要取得所有資料。 現在,讓我們來處理我們的星星建立/刪除路線。 轉到“src/app/api”並建立一個名為“repository”的新資料夾。在該資料夾中,建立一個名為「route.tsx」的新檔案。 在那裡加入以下程式碼: ``` import {getAllGithubStars} from "../../../../helper/all.stars"; import {prisma} from "../../../../helper/prisma"; import {Repository} from "@prisma/client"; import {getList} from "../../../../helper/get.list"; export async function POST(request: Request) { const body = await request.json(); if (!body.repository) { return new Response(JSON.stringify({error: 'Repository is required'}), {status: 400}); } const {owner, name} = body.repository.match(/github.com\/(?<owner>.*)\/(?<name>.*)/).groups; if (!owner || !name) { return new Response(JSON.stringify({error: 'Repository is invalid'}), {status: 400}); } if (body.todo === 'delete') { await prisma.repository.deleteMany({ where: { name: `${owner}/${name}` } }); return new Response(JSON.stringify({deleted: true}), {status: 200}); } const starsMonth = await getAllGithubStars(owner, name); const repo: Repository[] = []; for (const stars of starsMonth) { repo.push( await prisma.repository.upsert({ where: { name_day_month_year: { name: `${owner}/${name}`, month: stars.date.month, year: stars.date.year, day: stars.date.day, }, }, update: { stars: stars.stars, }, create: { name: `${owner}/${name}`, month: stars.date.month, year: stars.date.year, day: stars.date.day, stars: stars.stars, } }) ); } return new Response(JSON.stringify(await getList(repo)), {status: 200}); } ``` 我們共享 DELETE 和 CREATE 路由,這些路由通常不應在生產中使用,但我們在本文中這樣做是為了讓您更輕鬆。 我們從請求中取得 JSON,檢查「repository」欄位是否存在,並且它是 GitHub 儲存庫的有效路徑。 如果是刪除請求,我們使用 prisma 根據儲存庫名稱從資料庫中刪除儲存庫並傳回請求。 如果是建立,我們使用 getAllGithubStars 來獲取資料以保存到我們的資料庫中。 > 💡 由於我們已經在 `name`、`month`、`year` 和 `day` 上放置了唯一索引,如果記錄已經存在,我們可以使用 `prisma` `upsert` 來更新資料 最後,我們將新累積的資料回傳給客戶端。 最困難的部分完成了🍾 --- ## 主頁人口 💽 我們還沒有建立我們的主頁元件。 **我們開始做吧。** 前往“app”資料夾建立或編輯“page.tsx”並新增以下程式碼: ``` "use server"; import Main from "@/components/main"; import {getList} from "../../helper/get.list"; export default async function Home() { const list: any[] = await getList(); return ( <Main list={list} /> ) } ``` 我們使用與 getList 相同的函數來取得累積的所有儲存庫的所有資料。 我們還修改主要元件以支援它。 編輯 `components/main.tsx` 並將其替換為: ``` "use client"; import {useForm} from "react-hook-form"; import axios from "axios"; import {Repository} from "@prisma/client"; import {useCallback, useState} from "react"; interface List { name: string, list: Repository[] } export default function Main({list}: {list: List[]}) { const [repositoryState, setRepositoryState] = useState(list); const {register, handleSubmit} = useForm(); const submit = useCallback(async (data: any) => { const {data: repositoryResponse} = await axios.post('/api/repository', {todo: 'add', repository: data.name}); setRepositoryState([...repositoryState, ...repositoryResponse]); }, [repositoryState]) const deleteFromList = useCallback((val: List) => () => { axios.post('/api/repository', {todo: 'delete', repository: `https://github.com/${val.name}`}); setRepositoryState(repositoryState.filter(v => v.name !== val.name)); }, [repositoryState]) return ( <div className="w-full max-w-2xl mx-auto p-6 space-y-12"> <form className="flex items-center space-x-4" onSubmit={handleSubmit(submit)}> <input className="flex-grow p-3 border border-black/20 rounded-xl" placeholder="Add Git repository" type="text" {...register('name', {required: 'true'})} /> <button className="flex-shrink p-3 border border-black/20 rounded-xl" type="submit"> Add </button> </form> <div className="divide-y-2 divide-gray-300"> {repositoryState.map(val => ( <div key={val.name} className="space-y-4"> <div className="flex justify-between items-center py-10"> <h2 className="text-xl font-bold">{val.name}</h2> <button className="p-3 border border-black/20 rounded-xl bg-red-400" onClick={deleteFromList(val)}>Delete</button> </div> <div className="bg-white rounded-lg border p-10"> <div className="h-[300px]]"> {/* Charts Components */} </div> </div> </div> ))} </div> </div> ) } ``` --- ## 顯示圖表! 📈 前往“components”資料夾並新增一個名為“chart.tsx”的新檔案。 新增以下程式碼: ``` "use client"; import {Repository} from "@prisma/client"; import {useMemo} from "react"; import React from 'react'; import { Chart as ChartJS, CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend, } from 'chart.js'; import { Line } from 'react-chartjs-2'; ChartJS.register( CategoryScale, LinearScale, PointElement, LineElement, Title, Tooltip, Legend ); export default function ChartComponent({repository}: {repository: Repository[]}) { const labels = useMemo(() => { return repository.map(r => `${r.year}/${r.month}`); }, [repository]); const data = useMemo(() => ({ labels, datasets: [ { label: repository[0].name, data: repository.map(p => p.stars), borderColor: 'rgb(255, 99, 132)', backgroundColor: 'rgba(255, 99, 132, 0.5)', tension: 0.2, }, ], }), [repository]); return ( <Line options={{ responsive: true, }} data={data} /> ); } ``` 我們使用“chart.js”函式庫來繪製“Line”類型的圖表。 這非常簡單,因為我們在伺服器端完成了所有資料結構。 這裡需要注意的一件大事是我們「匯出預設值」我們的 ChartComponent。那是因為它使用了「Canvas」。這在伺服器端不可用,我們需要延遲載入該元件。 讓我們修改“main.tsx”: ``` "use client"; import {useForm} from "react-hook-form"; import axios from "axios"; import {Repository} from "@prisma/client"; import dynamic from "next/dynamic"; import {useCallback, useState} from "react"; const ChartComponent = dynamic(() => import('@/components/chart'), { ssr: false, }) interface List { name: string, list: Repository[] } export default function Main({list}: {list: List[]}) { const [repositoryState, setRepositoryState] = useState(list); const {register, handleSubmit} = useForm(); const submit = useCallback(async (data: any) => { const {data: repositoryResponse} = await axios.post('/api/repository', {todo: 'add', repository: data.name}); setRepositoryState([...repositoryState, ...repositoryResponse]); }, [repositoryState]) const deleteFromList = useCallback((val: List) => () => { axios.post('/api/repository', {todo: 'delete', repository: `https://github.com/${val.name}`}); setRepositoryState(repositoryState.filter(v => v.name !== val.name)); }, [repositoryState]) return ( <div className="w-full max-w-2xl mx-auto p-6 space-y-12"> <form className="flex items-center space-x-4" onSubmit={handleSubmit(submit)}> <input className="flex-grow p-3 border border-black/20 rounded-xl" placeholder="Add Git repository" type="text" {...register('name', {required: 'true'})} /> <button className="flex-shrink p-3 border border-black/20 rounded-xl" type="submit"> Add </button> </form> <div className="divide-y-2 divide-gray-300"> {repositoryState.map(val => ( <div key={val.name} className="space-y-4"> <div className="flex justify-between items-center py-10"> <h2 className="text-xl font-bold">{val.name}</h2> <button className="p-3 border border-black/20 rounded-xl bg-red-400" onClick={deleteFromList(val)}>Delete</button> </div> <div className="bg-white rounded-lg border p-10"> <div className="h-[300px]]"> <ChartComponent repository={val.list} /> </div> </div> </div> ))} </div> </div> ) } ``` 您可以看到我們使用“nextjs/dynamic”來延遲載入元件。 我希望將來 NextJS 能為客戶端元件加入類似「使用延遲載入」的內容 😺 --- ## 但是新星呢?來認識一下 Trigger.Dev! 每天加入新星星的最佳方法是執行 cron 請求來檢查新加入的星星並將其加入到我們的資料庫中。 不要使用 Vercel cron / GitHub 操作,或(上帝禁止)為此建立一個新伺服器。 我們可以使用 [Trigger.DEV](http://Trigger.DEV) 直接與我們的 NextJS 應用程式搭配使用。 那麼就讓我們來設定一下吧! 註冊 [Trigger.dev 帳號](https://trigger.dev/)。 註冊後,建立一個組織並為您的工作選擇一個專案名稱。 ![新組織](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bdnxq8o7el7t4utvgf1u.jpeg) 選擇 Next.js 作為您的框架,並按照將 Trigger.dev 新增至現有 Next.js 專案的流程進行操作。 ![NextJS](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e4kt7e5r1mwg60atqfka.jpeg) 否則,請點選專案儀表板側邊欄選單上的「環境和 API 金鑰」。 ![開發金鑰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ser7a2j5qft9vw8rfk0m.png) 複製您的 DEV 伺服器 API 金鑰並執行下面的程式碼片段以安裝 Trigger.dev。 仔細按照說明進行操作。 ``` npx @trigger.dev/cli@latest init ``` 在另一個終端中執行以下程式碼片段,在 Trigger.dev 和您的 Next.js 專案之間建立隧道。 ``` npx @trigger.dev/cli@latest dev ``` 讓我們建立 TriggerDev 作業! 您將看到一個新建立的資料夾,名為“jobs”。 在那裡建立一個名為“sync.stars.ts”的新文件 新增以下程式碼: ``` import { cronTrigger, invokeTrigger } from "@trigger.dev/sdk"; import { client } from "@/trigger"; import { prisma } from "../../helper/prisma"; import axios from "axios"; import { z } from "zod"; // Your first job // This Job will be triggered by an event, log a joke to the console, and then wait 5 seconds before logging the punchline. client.defineJob({ id: "sync-stars", name: "Sync Stars Daily", version: "0.0.1", // Run a cron every day at 23:00 AM trigger: cronTrigger({ cron: "0 23 * * *", }), run: async (payload, io, ctx) => { const repos = await io.runTask("get-stars", async () => { // get all libraries and current amount of stars return await prisma.repository.groupBy({ by: ["name"], _sum: { stars: true, }, }); }); //loop through all repos and invoke the Job that gets the latest stars for (const repo of repos) { getStars.invoke(repo.name, { name: repo.name, previousStarCount: repo?._sum?.stars || 0, }); } }, }); const getStars = client.defineJob({ id: "get-latest-stars", name: "Get latest stars", version: "0.0.1", // Run a cron every day at 23:00 AM trigger: invokeTrigger({ schema: z.object({ name: z.string(), previousStarCount: z.number(), }), }), run: async (payload, io, ctx) => { const stargazers_count = await io.runTask("get-stars", async () => { const { data } = await axios.get( `https://api.github.com/repos/${payload.name}`, { headers: { authorization: `token ${process.env.TOKEN}`, }, } ); return data.stargazers_count as number; }); await prisma.repository.upsert({ where: { name_day_month_year: { name: payload.name, month: new Date().getMonth() + 1, year: new Date().getFullYear(), day: new Date().getDate(), }, }, update: { stars: stargazers_count - payload.previousStarCount, }, create: { name: payload.name, stars: stargazers_count - payload.previousStarCount, month: new Date().getMonth() + 1, year: new Date().getFullYear(), day: new Date().getDate(), }, }); }, }); ``` 我們建立了一個名為“Sync Stars Daily”的新作業,該作業將在每天下午 23:00 執行 - 它在 cron 文本中的表示為:`0 23 * * *` 我們在資料庫中取得所有目前儲存庫,按名稱將它們分組,並對星星進行求和。 由於一切都在 Vercel 無伺服器上執行,因此我們可能會在檢查所有儲存庫時遇到逾時。 為此,我們將每個儲存庫傳送到不同的作業。 我們使用“invoke”建立新作業,然後在“獲取最新的星星”中處理它們 我們迭代所有新儲存庫並獲取當前的星星數量。 我們用舊的星星數量去除新的星星數量,得到今天的星星數量。 我們使用“prisma”將其新增至資料庫。沒有比這更簡單的了! 最後一件事是編輯“jobs/index.ts”並將內容替換為: ``` export * from "./sync.stars"; ``` 你就完成了🥳 --- ## 讓我們聯絡吧! 🔌 作為開源開發者,我們邀請您加入我們的[社群](https://discord.gg/nkqV9xBYWy),以做出貢獻並與維護者互動。請隨時造訪我們的 [GitHub 儲存庫](https://github.com/triggerdotdev/trigger.dev),貢獻並建立與 Trigger.dev 相關的問題。 本教學的源程式碼可在此處取得: [https://github.com/triggerdotdev/blog/tree/main/stars-monitor](https://github.com/triggerdotdev/blog/tree/main/stars-monitor) 感謝您的閱讀! --- 原文出處:https://dev.to/triggerdotdev/take-nextjs-to-the-next-level-create-a-github-stars-monitor-130a

使用 Services 和 RxJS 在 Angular 中進行簡單的狀態管理

原文出處:https://dev.to/avatsaev/simple-state-management-in-angular-with-only-services-and-rxjs-41p8 軟體開發中最具挑戰性的事情之一是狀態管理。目前,Angular 應用程式有幾個狀態管理庫:NGRX、NGXS、Akita...它們都有不同的狀態管理風格,最受歡迎的是 [NGRX](https://ngrx.io/),它幾乎遵循React 世界的FLUX/Redux 原則(基本上使用單向資料流和不可變資料結構,但使用RxJS可觀察流)。 但是,如果您不想學習、設定、使用整個狀態管理庫,也不想處理一個簡單專案的所有樣板文件,如果您只想使用您已經熟悉的工具來**管理狀態,該怎麼辦?Anular 開發人員 * *,並且仍然獲得狀態管理庫提供的效能最佳化和一致性(推送變更偵測,一種不可變資料流)。 **免責聲明:這不是針對狀態管理庫的帖子。我們確實在工作中使用NGRX,它確實幫助我們在非常大和複雜的應用程式中管理非常複雜的狀態,但正如我常說的,NGRX 使簡單應用程式的事情變得複雜,並簡化了複雜應用程式的事情,請記住這一點。* * 在這篇文章中,我將向您展示一種僅使用 **RxJS** 和 **依賴注入** 來管理狀態的簡單方法,我們所有的元件樹都將使用 OnPush 更改檢測策略。 想像我們有一個簡單的 Todo 應用程式,我們想要管理它的狀態,我們已經設定了元件,現在我們需要一個服務來管理狀態,讓我們建立一個簡單的 Angular 服務: ``` // todos-store.service.ts @Injectable({provideIn: 'root'}) export class TodosStoreService { } ``` 所以我們需要的是,一種提供待辦事項清單的方法,一種加入、刪除、過濾和完成待辦事項的方法,我們將使用 getter/setter 和 RxJS 的行為主題來執行此操作: 首先我們建立在 todos 中讀寫的方法: ``` // todos-store.service.ts @Injectable({provideIn: 'root'}) export class TodosStoreService { // - We set the initial state in BehaviorSubject's constructor // - Nobody outside the Store should have access to the BehaviorSubject // because it has the write rights // - Writing to state should be handled by specialized Store methods (ex: addTodo, removeTodo, etc) // - Create one BehaviorSubject per store entity, for example if you have TodoGroups // create a new BehaviorSubject for it, as well as the observable$, and getters/setters private readonly _todos = new BehaviorSubject<Todo[]>([]); // Expose the observable$ part of the _todos subject (read only stream) readonly todos$ = this._todos.asObservable(); // the getter will return the last value emitted in _todos subject get todos(): Todo[] { return this._todos.getValue(); } // assigning a value to this.todos will push it onto the observable // and down to all of its subsribers (ex: this.todos = []) private set todos(val: Todo[]) { this._todos.next(val); } addTodo(title: string) { // we assaign a new copy of todos by adding a new todo to it // with automatically assigned ID ( don't do this at home, use uuid() ) this.todos = [ ...this.todos, {id: this.todos.length + 1, title, isCompleted: false} ]; } removeTodo(id: number) { this.todos = this.todos.filter(todo => todo.id !== id); } } ``` 現在讓我們建立一個方法來設定待辦事項的完成狀態: ``` // todos-store.service.ts setCompleted(id: number, isCompleted: boolean) { let todo = this.todos.find(todo => todo.id === id); if(todo) { // we need to make a new copy of todos array, and the todo as well // remember, our state must always remain immutable // otherwise, on push change detection won't work, and won't update its view const index = this.todos.indexOf(todo); this.todos[index] = { ...todo, isCompleted } this.todos = [...this.todos]; } } ``` 最後是一個可觀察的來源,它將只為我們提供已完成的待辦事項: ``` // todos-store.service.ts // we'll compose the todos$ observable with map operator to create a stream of only completed todos readonly completedTodos$ = this.todos$.pipe( map(todos => todos.filter(todo => todo.isCompleted)) ) ``` 現在,我們的待辦事項商店看起來像這樣: ``` // todos-store.service.ts @Injectable({providedIn: 'root'}) export class TodosStoreService { // - We set the initial state in BehaviorSubject's constructor // - Nobody outside the Store should have access to the BehaviorSubject // because it has the write rights // - Writing to state should be handled by specialized Store methods (ex: addTodo, removeTodo, etc) // - Create one BehaviorSubject per store entity, for example if you have TodoGroups // create a new BehaviorSubject for it, as well as the observable$, and getters/setters private readonly _todos = new BehaviorSubject<Todo[]>([]); // Expose the observable$ part of the _todos subject (read only stream) readonly todos$ = this._todos.asObservable(); // we'll compose the todos$ observable with map operator to create a stream of only completed todos readonly completedTodos$ = this.todos$.pipe( map(todos => todos.filter(todo => todo.isCompleted)) ) // the getter will return the last value emitted in _todos subject get todos(): Todo[] { return this._todos.getValue(); } // assigning a value to this.todos will push it onto the observable // and down to all of its subsribers (ex: this.todos = []) private set todos(val: Todo[]) { this._todos.next(val); } addTodo(title: string) { // we assaign a new copy of todos by adding a new todo to it // with automatically assigned ID ( don't do this at home, use uuid() ) this.todos = [ ...this.todos, {id: this.todos.length + 1, title, isCompleted: false} ]; } removeTodo(id: number) { this.todos = this.todos.filter(todo => todo.id !== id); } setCompleted(id: number, isCompleted: boolean) { let todo = this.todos.find(todo => todo.id === id); if(todo) { // we need to make a new copy of todos array, and the todo as well // remember, our state must always remain immutable // otherwise, on push change detection won't work, and won't update its view const index = this.todos.indexOf(todo); this.todos[index] = { ...todo, isCompleted } this.todos = [...this.todos]; } } } ``` 現在我們的智慧元件可以存取商店並輕鬆操作它: *(PS:我建議使用[ImmutableJS](https://immutable-js.github.io/immutable-js)而不是手動管理不變性)* ``` // app.component.ts export class AppComponent { constructor(public todosStore: TodosStoreService) {} } ``` ``` <!-- app.component.html --> <div class="all-todos"> <p>All todos</p> <app-todo *ngFor="let todo of todosStore.todos$ | async" [todo]="todo" (complete)="todosStore.setCompleted(todo.id, $event)" (remove)="todosStore.removeTodo($event)" ></app-todo> </div> ``` 這是完整的最終結果: [StackBlitz 上具有真實 REST API 的完整範例](https://stackblitz.com/edit/angular-rxjs-store?file=src%2Fapp%2Ftodos-store.service.ts) 這也是一種可擴展的狀態管理方式,您可以使用Angular 強大的DI 系統輕鬆地將其他儲存服務注入彼此,將其可觀察量與管道運算符結合起來以建立更複雜的可觀察量,並注入HttpClient 等服務以從伺服器提取資料例如。無需所有 NGRX 樣板或安裝其他狀態管理庫。盡可能保持簡單和輕鬆。 --- 在 Twitter 上關注我,以了解更多有趣的 Angular 相關內容:https://twitter.com/avatsaev

大型團隊中程式碼審查的實用技巧

原文出處:https://dev.to/rchugunov/practical-tips-for-code-reviews-in-large-teams-25nb 改進程式碼審查流程對於旨在維持和提高效率和程式碼品質的開發團隊至關重要。越來越多的待處理拉取請求 (PR) 清單可能會令人不知所措,甚至令人士氣低落。透過完善審核流程,團隊可以確保 PR 的均衡分配,防止某些團隊成員被淹沒而其他成員閒置。爭取平等地花在公關上的時間有助於創造一個有凝聚力、和諧的團隊環境。此外,遵守旨在將審核時間控制在**一個工作日**的標準可保證快速反饋並促進動態、響應迅速的開發週期。最後,改進工作的本質是提高 PR 的質量,確保 PR 的規模最佳、準備充分且全面,從而簡化整個開發流程。 ## 如何衡量程式碼審查的有效性 為了衡量程式碼審查流程的有效性,必須專注於團隊績效而不是個人貢獻。關鍵指標包括拉取請求 (PR) 接受審查的持續時間以及 PR 處於審查階段的時間相對於其總程式碼行數的時間。監控保持開放的 PR 數量以及每個 PR 中的程式碼量可以進一步深入了解審核流程的效率。 - 衡量團隊的效率而不是某些人的效率 - 測量 PR 處於審核狀態的時間。 - 測量 PR 處於審核狀態的時間除以程式碼行數。 - 處於開放狀態的 PR 數量。 - PR 中的程式碼行 這可以透過引入收集 PR 資訊的工具來實現。如果你使用 Github,有一個 github 操作 [issue-metrics](https://github.com/github/issue-metrics) 可以測量 PR 在一定時間內處於審核狀態的平均時間。但是您可以使用 Github API 建立自己的操作,該操作將收集對您的專案重要的資訊。 ![issue-metrics 產生的報告範例](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kavvtr1qq6437brkeq93.png) ## 準備好你的 PR 始終首先向您的 PR 加入**詳細描述**。如果視覺表示有幫助,請考慮使用圖表。提出**審核計劃**也可以改變遊戲規則,引導審核者按照邏輯順序進行操作,確保任何更改都不會被忽視。 在您請求其他人深入研究您的程式碼之前,請先自己查看您的 PR 草案。透過這種自我審查,您可以發現並清除任何零散的評論或疏忽。 PR 中的評論應該澄清您的編碼決策,尤其是在可能出現混淆的情況下。例如,如果您在目前 PR 期間解決了一個不相關的錯誤,請提及它。這種先發制人的澄清可以讓審稿人省去很多麻煩。註釋充當更改的路線圖。透過引導審閱者查看特定文件或解釋某些修改背後的理由,您可以使他們的工作變得更簡單。額外的福利?您可能會在此註釋階段發現錯誤,甚至在審查開始之前修復它們。 如果您在 PR 中解決了多個問題,則可能需要將其分開。 **PR 應該簡潔且重點突出。** 經驗法則:如果更改涉及超過 5 個文件、花費了一天的時間來起草,或者需要大量的審查時間,則將其拆分。例如,一個 PR 可以為一項新功能佈置 API,而後續的 PR 可以展示實作。 ## 如何查看別人的 PR 與任何其他任務一樣重視程式碼審查。在日曆中劃出專門用於複習的常規時間段。 **快速回饋至關重要 - 開發人員等待的時間越長,上下文就會變得越模糊,從而使採納建議變得困難**。 程式碼審查不僅僅是為了發現錯誤。它們提供了一個熟悉團隊不斷發展的功能和編碼原則的機會。抓住這個學習和成長的機會。 您在審核期間的評論應該清晰且具有建設性。模糊的言論可能會導致混亂。始終致力於提供回饋,指導開發人員實現預期的解決方案。 雖然像 GitHub 這樣的平台非常適合程式碼託管和初步審查,但它們可能不是最適合擴展討論的平台。考慮將長時間的對話轉移到像 Slack 這樣的平台上,以進行更有活力的交流。 對於大量拉取請求,將分支拉入本機開發環境可能會很有幫助。 **IntelliJ Idea** 等工具可以提供更身臨其境的差異視圖。請記住使用“git merge -no-commit -no-ff”等命令來查看更改,就像您所做的那樣。 ![拉入 IntelliJ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xlxegquppgof12fv4cob.png) 如果您發現程式碼的某些部分難以掌握,請隨時向作者詢問清楚。最好停下來理解一下,而不是根據假設提供回饋。 ## 審稿人分配演算法 有多種方法可以自動為 PR 指派審閱者。例如隨機或使用矩陣方法。 GitHub 提供了兩個策略 https://docs.github.com/en/organizations/organizing-members-into-teams/managing-code-review-settings-for-your-team#about-auto-assignment 另一種方法是製定自訂策略,其中每個團隊成員都有來自他的團隊的審核者列表,但也有來自其他團隊的兩名臨時審核者。 **考慮團隊規模和功能交付速度,選擇最適合您團隊的方法。** ## 程式碼審查的速度 雖然立即審查是理想的選擇,但並不總是可行。儘管如此,要遵守的黃金法則是**24 小時時間範圍**。目標是在一個工作天內回覆程式碼審查請求,即使這只是初步評估。這確保了程式碼不會停留在審查的邊緣,這可能會延遲後續的開發階段。 透過遵守此規則,如有必要,典型的變更清單 (CL) 可能會在一天內經歷多輪審核。如此快速的周轉不僅簡化了開發流程,而且還促進了審閱者和開發人員之間的動態討論,從而形成更加完善的程式碼庫。 ## 如何處理審稿意見 不要只依賴 Github 評論,而是使用 **Slack Github 連結** 來促進 PR 上的溝通。它為即時互動提供了一個動態平台,使澄清疑慮、尋求解釋並就建議的變更達成共識變得更加容易。 如果您打算稍後解決特定評論或問題,請留下 **TODO** 標籤以及任務編號。這可以確保您對待處理的操作有清晰的路線圖,並且這些任務在未來的開發階段不會被忽略。 如果某個特定的程式碼部分引發了長時間的爭論,那麼記錄所做的決定就至關重要。 **透過加入解釋選擇和理由的註釋,可以防止將來重複討論。**它可以作為參考,確保未來的開發人員或審閱者了解特定程式碼片段背後的上下文和推理。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wj42qr3oq1s3iu6etfi8.png) ## 連結 Google指南:[程式碼審查開發者指南](https://google.github.io/eng-practices/review/) 思科研究:https://static1.smartbear.co/support/media/resources/cc/book/code-review-cisco-case-study.pdf Microsoft:[來自 Microsoft 的 30 個經過驗證的程式碼審查最佳實踐 - McKayla 博士](https://www.michaelagreiler.com/code-review-best-practices/#practicereviewers) 更多關於 CR 的閱讀:https://blog.palantir.com/code-review-best-practices-19e02780015f

自己用 20 行 JavaScript 來寫螢幕錄影功能!

假設您厭倦了螢幕錄影機的付費專區和限制,並想繼續編寫自己的程式碼 - 事實證明您已經可以透過幾行程式碼獲得基本功能。 原文出處:https://dev.to/ninofiliu/simple-screen-recorder-in-20-lines-of-javascript-4ina 我們可以要求瀏覽器使用[螢幕擷取API](https://developer.mozilla.org/en-US/docs/Web/API/Screen_Capture_API/Using_Screen_Capture)為我們取得擷取視訊串流,但出於安全原因我們必須確保[使用者手勢](https://stackoverflow.com/q/56388258/8186898)觸發捕獲,例如點擊按鈕: ``` const button = document.createElement("button"); button.innerHTML = "capture"; document.body.append(button); button.addEventListener("click", async () => { // TODO }); ``` 點擊後,獲取視訊串流並進行錄製 ``` const stream = await navigator.mediaDevices.getDisplayMedia(); const recoder = new MediaRecorder(stream); recoder.start(); ``` 當使用者停止分享螢幕時停止錄製 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3k0wtf5udsvefz3hl88e.png) ``` const [video] = stream.getVideoTracks(); video.addEventListener("ended", () => { recoder.stop(); }); ``` 取得錄音檔案並下載 ``` recoder.addEventListener("dataavailable", (evt) => { const a = document.createElement("a"); a.href = URL.createObjectURL(evt.data); a.download = "capture.webm"; a.click(); }); ``` 瞧,你就有了一個簡單的螢幕錄影機! 它有很多解決起來很有趣的限制- 音頻錄製、網絡攝像頭集成、長時間執行的流等- 但我剛剛發現用這麼少的程式碼行就可以完成如此強大的事情,這太棒了,無法不分享。 [codepen連結](https://codepen.io/ninofiliu/embed/BaMzxQM)

【前端動手玩創意】動態生成的藝術|小心,亂改DOM你可能會被打臉。

## 目錄 ##### [【前端動手玩創意】等待的轉圈圈效果 (1)](https://ithelp.ithome.com.tw/articles/10311621) ##### [【前端動手玩創意】google五星評分的星星(2)](https://ithelp.ithome.com.tw/articles/10311643) ##### [【前端動手玩創意】CSS-3D卡片翻轉效果(3) (今天難度頗高,想挑戰再進來!)](https://ithelp.ithome.com.tw/articles/10311672) ##### [【前端動手玩創意】一句CSS做出好看的hero section!(4)](https://ithelp.ithome.com.tw/articles/10311691) ##### [【前端動手玩創意】創造一個Skill bar(5)](https://ithelp.ithome.com.tw/articles/10311756) ##### [【前端動手玩創意】遮蔽廣告(D卡未登入)腳本、自定義新增名單(6)](https://ithelp.ithome.com.tw/articles/10311999) ##### [【前端動手玩創意】前端canvas截圖的招式!竟然有三招,可存成SVG或PNG (7)](https://ithelp.ithome.com.tw/articles/10312001) ##### [【前端動手玩創意】讓你的PDF檔案更難被抓取(8)](https://ithelp.ithome.com.tw/articles/10312046) ##### [【前端動手玩創意】哇操!你敢信?花式寫todo-list,body裡面一行都沒有也能搞?(9)](https://ithelp.ithome.com.tw/articles/10312056) ##### [【前端動手玩創意】卡片製作,才不是!是卡片製作器!(10)](https://ithelp.ithome.com.tw/articles/10312066) ##### [【前端動手玩創意】太屌了吧!?用Class(類)製作Jquery的效果!(11)](https://ithelp.ithome.com.tw/articles/10312114) ##### [ 【前端動手玩創意】置頂按鈕,老梗經典|帶你的網頁搭電梯(12)](https://ithelp.ithome.com.tw/articles/10312922) ## 前情提要 一陣子沒寫前端動手玩創意了 今天要來點好料的 我們談談關於藝術 對 就算是寫程式我們也是可以有藝術氣息的 別這麼驚訝XD 假設我有一組資料 一般人來說 最直覺的就是把html裡面的元素寫出來寫死 直覺菜鳥就是寫出來啊 ``` <div id="items_list"> <li class="buy_item">1.紅茶 <div class="price">10</div> <div class="del_btn">X</div> </li> <li class="buy_item">2.奶茶 <div class="price">15</div> <div class="del_btn">X </div> </li> <li class="buy_item">3.綠茶 <div class="price">30</div> <div class="del_btn">X</div> </li> </div> ``` 要更新則是就去更改DOM就好了 反正我都學會JS了 有什麼大不了(? 但是現在已經進入大前端時代了就算你寫原生 也會有data model的概念 這部分可以參考站長阿川寫過的好文 裡面的文筆跟邏輯 不誇張 是我見過「華文圈寫得最好的前端教學」 尤其就是這篇 關於data model的介紹 切入點非常的有趣也很有道理 有興趣的自己去花心思讀看看 [認識 data model 與 render function](https://codelove.tw/@howtomakeaturn/post/9xLo5q) 稍微有點料的前端學習者 本身就會寫一寫 想說:既然有一隻API是createElement 那是不是我可以整個html都用js寫出來(? 這是個超級有趣的觀點 ## 關於data render的概念: 「是不是我可以整個html都用js寫出來」 相傳牛頓提出三大定律以後 認為地球和八大行星一開始的慣性力叫「上帝的第一推動力」 實際上這個: 「整個html都用js寫出來」 也是推動前端往框架邁進的思考第一步 可以說是前端慣性的上帝推力了 當然如果你有打籃球 也可以比喻成上籃的第零步XD ## 觀念筆記 ### html程式碼 ``` <div id="buylist"> <h1>myBuylist 購物清單</h1> <div class="buyitem"> <label>產品名</label> <input/> <label>價錢</label> <input/><span class="addbtn">+新增</span> </div> <div id="items_list">這邊準備用JS插入東西所以這段只是說明文字</div> </div> ``` 把整個頁面的元素寫出來 但是資料的區塊保留著 因為等等我們要用JS的API去動態生成 未來直接data render 方便更新與管理 ### JS程式碼 ``` var shoplist = {}; shoplist.name = "購物清單"; shoplist.list = [ { name: "吹風機", price: "300" }, { name: "麥克筆", price: "20" }, { name: "筆記型電腦", price: "29300" }, { name: "Iphone 9", price: "5200" }, { name: "神奇海螺", price: "1000" }, ]; var item_html = "<li id={{id}} class='buy_item'>{{name}}<div class='price'>{{price}}</div><div class='del_btn'>X</div></li>"; var total_html = "<li class='buy_item total'>總價<div class='price'>{{price}}</div><div class='del_btn'>X</div></li>"; var total_price = 0; for (var i=0; i < shoplist.list.length; i++) { var item = shoplist.list[i]; total_price += item.price; var current_item_html = item_html.replace("{{num}}", i + 1) .replace("{{name}}", item.name) .replace("{{id}}", "buyitem_" + i) .replace("{{price}}", item.price); $("#items_list").append(current_item_html); } ``` 這邊值得關注的一點是資料的處理 也就是數據結構上使用物件與陣列去儲存資料 為什麼要學 陣列 為什麼要學物件 這兩個都是抽象的名詞 他們都是為了來處理資料所規劃的兩種不同內容 ## 關於物件與陣列 物件就像是RPG角色 會有很多的屬性 魔法 敏捷 力量 血量 這些屬性都是被附加在person上面 所以person.blood是一個資料 person.power是一個資料 person.magic是一個資料 最後都存在person裡面 這個person就是一個含有很多屬性的物件 感覺就是有血有肉很3D 而陣列就比較平面化 就是很多數字排成一列而已 其實沒什麼特別需要關注的 這兩個也不會不好區分 只要稍微做個比喻 都很好理解 以我們的code來講解 shoplist就是一個物件 含有一些屬性 包含名字與清單 因為清單很多 所以清單用一個陣列儲存 陣列裡面放很多個物件 這些物件就是每一個清單包含的那些購買項目 其實不用太在意誰是誰因為用看的就很清楚 最後我們用迴圈去把shoplist裡面的每一筆資料都丟進去 中途replace是文字處理 把我們設置的{{name}}這種花括號的東西換成真實資料 這部分有點樣板語言的感覺XD 其實非常有趣 很值得玩味 ## 心得 這次比較多實在的JS程式碼 就不只是玩玩切版了 算是有點靠近框架的部分(◉3◉) 動手玩創意這個系列其實靈魂之處就在於「有趣」兩個字 坊間把前端描繪成為了找工作的銅臭味 以及把切版講成無聊的工匠苦力活 我認為都是錯誤的解讀 我認為 只要是有趣的地方就是前端最有價值的地方 而不是誰學了那個框架 誰又認為哪個東西比較厲害 哪個語言比較屌 那都是很無聊的文字遊戲罷了 如果你喜歡這樣子的前端 請跟著這個系列繼續走(→ܫ←) 我們才只是在桃花源外的小溪旁玩水而已呢! 未來會往天空飛翔哦XD

一位資深軟體工程師的 VSCode 設定方式&外掛套件分享

資深開發者 Jatin Sharma 在國外論壇分享了個人使用的 VSCode 設定,內容豐富,跟大家分享! 原文出處:https://dev.to/j471n/my-vs-code-setup-971 ## 🎨主題 我使用 [**Andromeda**](https://marketplace.visualstudio.com/items?itemName=EliverLara.andromeda) 作為我的 VS Code 的主要主題 ![andromeda-截圖](https://res.cloudinary.com/practicaldev/image/fetch/s--bw_aagIQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_800/https://github.com/EliverLara/Andromeda/raw/master/images/andromeda.png) ## 🪟圖標 對於圖標,我會在 [**材質圖標主題**](https://marketplace.visualstudio.com/items?itemName=PKief.material-icon-theme) 和 [**材質主題圖標**]( https://marketplace.visualstudio.com/items?itemName=Equinusocio.vsc-material-theme-icons) **找找看。** ### 材質圖標主題 ![材質圖標主題](https://i.imgur.com/xA90m2X.png) ### 材質主題圖標 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675233057115/b8d1623c-a092-475e-a66a-91b4a42e5441.png) ## ⚒️外掛 最讚的部分來了,有很多擴展我只提到了我最喜歡的或我每天主要使用的擴展。 ### 自動重命名標籤 自動重命名配對的 HTML/XML 標記,與 Visual Studio IDE 的操作相同。 **下載:** [**自動重命名標籤**](https://marketplace.visualstudio.com/items?itemName=formulahendry.auto-rename-tag) ![](https://github.com/formulahendry/vscode-auto-rename-tag/raw/HEAD/images/usage.gif) ### 括號對著色切換器 VS Code 擴展,為您提供一個簡單的命令來快速切換全局“括號對著色” **下載:** [**括號對著色切換器**](https://marketplace.visualstudio.com/items?itemName=dzhavat.bracket-pair-toggler) ![](https://github.com/dzhavat/bracket-pair-toggler/raw/HEAD/assets/bracket-pair-toggler-demo.gif) ### C/C++ C/C++ 擴展向 Visual Studio Code 加入了對 C/C++ 的語言支持,包括編輯 (IntelliSense) 和除錯功能。 **下載:** [**C/C++**](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools) ![](https://i.imgur.com/0syu1Ym.png) ### 程式碼執行器 執行多種語言的程式碼片段或程式碼文件 **下載:** [**程式碼執行器**](https://marketplace.visualstudio.com/items?itemName=formulahendry.code-runner) ![用法](https://github.com/formulahendry/vscode-code-runner/raw/HEAD/images/usage.gif) ### 程式碼拼寫檢查器 一個基本的拼寫檢查器,可以很好地處理程式碼和文件。 該拼寫檢查器的目標是幫助發現常見的拼寫錯誤,同時保持較低的誤報數量。 **下載:** [**程式碼拼寫檢查器**](https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker) ![示例](https://raw.githubusercontent.com/streetsidesoftware/vscode-spell-checker/main/images/example.gif) ### DotENV VSCode `.env` 語法高亮。 **下載:** [**DotENV**](https://marketplace.visualstudio.com/items?itemName=mikestead.dotenv) ![示例](https://github.com/mikestead/vscode-dotenv/raw/master/images/screenshot.png) ### 錯誤鏡頭 ErrorLens 通過使診斷更加突出來增強語言診斷功能,突出顯示語言生成的診斷的整行,並內聯打印訊息。 **下載:** [**錯誤鏡頭**](https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens) ![演示圖片](https://raw.githubusercontent.com/usernamehw/vscode-error-lens/master/img/demo.png) ### ES7+ React/Redux/React-Native 片段 ES7+ 中的 JavaScript 和 React/Redux 片段以及 [VS Code](https://code.visualstudio.com/) 的 Babel 插件功能 **下載:** [**ES7+ React/Redux/React-Native 片段**](https://marketplace.visualstudio.com/items?itemName=dsznajder.es7-react-js-snippets) ![](https://i.imgur.com/cYpm6cw.png) ### ESLint 該擴展使用安裝在打開的工作區文件夾中的 ESLint 庫。如果該文件夾未提供,則擴展程序將查找全局安裝版本。如果您尚未在本地或全局安裝 ESLint,請在工作區文件夾中執行“npm install eslint”進行本地安裝,或執行“npm install -g eslint”進行全局安裝。 **下載:** [**ESLint**](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint) ![](https://i.imgur.com/R3o4517.png) ### Git 圖 查看存儲庫的 Git 圖表,並從圖表中輕鬆執行 Git 操作。可配置為您想要的外觀! **下載:** [Git Graph](https://marketplace.visualstudio.com/items?itemName=mhutchie.git-graph) ![Git Graph 記錄](https://github.com/mhutchie/vscode-git-graph/raw/master/resources/demo.gif) ### GitLens GitLens **增強了 VS Code 中的 Git,並解鎖每個存儲庫中**未開發的知識**。它可以幫助您通過 Git Blame 註釋和 CodeLens 一目了然地**可視化程式碼作者**,**無縫導航和探索** Git 存儲庫,**通過豐富的可視化和強大的比較命令**獲得有價值的見解**,等等更多的。 **下載:** [**GitLens**](https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens) ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675224552887/688896dd-cfff-41fc-aa2e-53716e5585c6.png) ### HTML 樣板 此擴展提供了所有 Web 應用程式中使用的標準 HTML 樣板程式碼。 **下載:** [**HTML 樣板**](https://marketplace.visualstudio.com/items?itemName=sidthesloth.html5-boilerplate) ![替代文本](https://s19.postimg.cc/3mig98d5v/html_boilerplate_1_0_3.gif) ### Import Cost 此擴展將在編輯器中內聯顯示導入包的大小。該擴展利用 webpack 來檢測導入的大小。 **下載:** [**Import Cost**](https://marketplace.visualstudio.com/items?itemName=wix.vscode-import-cost) ![示例圖片](https://citw.dev/_next/image?url=%2fposts%2fimport-cost%2f1quov3TFpgG2ur7myCLGtsA.gif&w=1080&q=75) ### Live Server 它將啟用實時更改而不保存文件。 **下載:** [**Live Server**](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer) ![實時伺服器演示 VSCode](https://github.com/ritwickdey/vscode-live-server/raw/HEAD/images/Screenshot/vscode-live-server-animated-demo.gif) ### Markdown 多合一 Markdown 所需的一切(鍵盤快捷鍵、目錄、自動預覽等)。 ***注意***:VS Code 具有開箱即用的基本 Markdown 支持(例如,**Markdown 預覽**),請參閱官方文件了解更多訊息。 **下載:** [**Markdown All in One**](https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one) ![切換粗體gif](https://github.com/yzhang-gh/vscode-markdown/raw/master/images/gifs/toggle-bold.gif) ### Markdown 預覽增強 它顯示了 Markdown 內容的增強預覽。 **下載:** [**Markdown 預覽增強版**](https://marketplace.visualstudio.com/items?itemName=shd101wyy.markdown-preview-enhanced) ![簡介](https://user-images.githubusercontent.com/1908863/28495106-30b3b15e-6f09-11e7-8eb6-ca4ca001ab15.png) ### 將 JSON 粘貼為程式碼 複製 JSON,粘貼為 Go、TypeScript、C#、C++ 等。 **下載 -** [**將 JSON 粘貼為程式碼**](https://marketplace.visualstudio.com/items?itemName=quicktype.quicktype) ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llqdlpz0amo1vj7m5no5.png) ### 更漂亮 使用 Prettier 的程式碼格式化程序 **下載 -** [**Prettier**](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) ![更漂亮](https://i.imgur.com/wHlMe9e.png) ### Python IntelliSense (Pylance)、Linting、除錯(多線程、遠程)、Jupyter Notebooks、程式碼格式化、重構、單元測試等。 **下載 -** [**Python**](https://marketplace.visualstudio.com/items?itemName=ms-python.python) ![Python](https://i.imgur.com/cQ1ARrG.png) ### 設置同步 使用 GitHub Gist 跨多台計算機同步設置、程式碼片段、主題、文件圖標、啟動、按鍵綁定、工作區和擴展。 **下載 -** [**設置同步**](https://marketplace.visualstudio.com/items?itemName=Shan.code-settings-sync) ![設置同步](https://shanalikhan.github.io/img/login-with-github.png) ### Tailwind CSS IntelliSense 適用於 VS Code 的智能 Tailwind CSS 工具 **下載 -** [**Tailwind CSS IntelliSense**](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) ![Tailwind CSS IntelliSense](https://raw.githubusercontent.com/bradlc/vscode-tailwindcss/master/packages/vscode-tailwindcss/.github/banner.png) ### 所有亮點 突出顯示程式碼中的“TODO”、“FIXME”和其他註釋。 有時,在將程式碼發佈到生產環境之前,您會忘記檢查編碼時加入的 TODO。所以我長期以來一直想要一個擴展來突出顯示它們並提醒我還有註釋或尚未完成的事情。 希望這個擴展也能幫助您。 **下載 -** [**TODO 突出顯示**](https://marketplace.visualstudio.com/items?itemName=wayou.vscode-todo-highlight) ![TODO 突出顯示](https://github.com/wayou/vscode-todo-highlight/raw/master/assets/material-night.png) ### Turbo 控制台日誌 自動編寫有意義的日誌訊息的過程。 **下載 -** [**Turbo 控制台日誌**](https://marketplace.visualstudio.com/items?itemName=ChakrounAnas.turbo-console-log) ![Turbo 控制台日誌](https://image.ibb.co/dysw7p/insert_log_message.gif) ### 塔布寧人工智能 Tabnine 是一款 AI 程式碼助手,可讓您成為更好的開發人員。 Tabnine 將通過所有最流行的編碼語言和 IDE 中的實時程式碼完成來提高您的開發速度。 **下載 -** [**Tabnine AI**](https://marketplace.visualstudio.com/items?itemName=TabNine.tabnine-vscode) ![Tabnine AI](https://raw.githubusercontent.com/codota/tabnine-vscode/master/assets/completions-main.gif) ## ⚙️設置 以下“JSON”程式碼顯示了我的 VS Code 設置: ``` // user/settings.json { "files.autoSave": "afterDelay", "editor.mouseWheelZoom": true, "code-runner.clearPreviousOutput": true, "code-runner.ignoreSelection": true, "code-runner.runInTerminal": true, "code-runner.saveAllFilesBeforeRun": true, "code-runner.saveFileBeforeRun": true, "editor.wordWrap": "on", "C_Cpp.updateChannel": "Insiders", "editor.suggestSelection": "first", "python.jediEnabled": false, "editor.fontSize": 17, "emmet.includeLanguages": { "javascript": "javascriptreact" }, "editor.minimap.size": "fit", "editor.fontFamily": "Consolas, DejaVu Sans Mono, monospace", "editor.fontLigatures": false, "[html]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "python.formatting.provider": "yapf", "[css]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "git.autofetch": true, "git.enableSmartCommit": true, "html-css-class-completion.enableEmmetSupport": true, "editor.formatOnPaste": true, "liveServer.settings.donotShowInfoMsg": true, "[python]": { "editor.defaultFormatter": "ms-python.python" }, "diffEditor.ignoreTrimWhitespace": false, "[json]": { "editor.defaultFormatter": "vscode.json-language-features" }, "[c]": { "editor.defaultFormatter": "ms-vscode.cpptools" }, "editor.fontWeight": "300", "editor.fastScrollSensitivity": 6, "explorer.confirmDragAndDrop": false, "vsicons.dontShowNewVersionMessage": true, "workbench.iconTheme": "material-icon-theme", "editor.defaultFormatter": "esbenp.prettier-vscode", "editor.renderWhitespace": "none", "workbench.startupEditor": "newUntitledFile", "liveServer.settings.multiRootWorkspaceName": "", "liveServer.settings.port": 5000, "liveServer.settings.donotVerifyTags": true, "editor.formatOnSave": true, "html.format.indentInnerHtml": true, "editor.formatOnType": true, "printcode.tabSize": 4, "terminal.integrated.confirmOnExit": "hasChildProcesses", "terminal.integrated.cursorBlinking": true, "terminal.integrated.rightClickBehavior": "default", "tailwindCSS.emmetCompletions": true, "sync.gist": "527c3e29660c53c3f17c32260188d66d", "gitlens.hovers.currentLine.over": "line", "terminal.integrated.profiles.windows": { "PowerShell": { "source": "PowerShell", "icon": "terminal-powershell" }, "Command Prompt": { "path": [ "${env:windir}\\Sysnative\\cmd.exe", "${env:windir}\\System32\\cmd.exe" ], "args": [], "icon": "terminal-cmd" }, "Git Bash": { "source": "Git Bash" }, "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe (migrated)": { "path": "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe", "args": [] }, "Windows PowerShell": { "path": "C:\\WINDOWS\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" }, "Ubuntu (WSL)": { "path": "C:\\WINDOWS\\System32\\wsl.exe", "args": [ "-d", "Ubuntu" ] } }, "javascript.updateImportsOnFileMove.enabled": "always", "[dotenv]": { "editor.defaultFormatter": "foxundermoon.shell-format" }, "editor.tabSize": 2, "cSpell.customDictionaries": { "custom-dictionary-user": { "name": "custom-dictionary-user", "path": "~/.cspell/custom-dictionary-user.txt", "addWords": true, "scope": "user" } }, "window.restoreFullscreen": true, "tabnine.experimentalAutoImports": true, "files.defaultLanguage": "${activeEditorLanguage}", "bracket-pair-colorizer-2.depreciation-notice": false, "workbench.editor.wrapTabs": true, "[markdown]": { "editor.defaultFormatter": "esbenp.prettier-vscode" }, "[ignore]": { "editor.defaultFormatter": "foxundermoon.shell-format" }, "terminal.integrated.fontFamily": "courier new", "terminal.integrated.defaultProfile.windows": "pwsh.exe -nologo", "terminal.integrated.shellIntegration.enabled": true, "terminal.integrated.shellIntegration.showWelcome": false, "editor.accessibilitySupport": "off", "editor.bracketPairColorization.enabled": true, "todohighlight.isEnable": true, "terminal.integrated.shellIntegration.history": 1000, "turboConsoleLog.insertEnclosingClass": false, "turboConsoleLog.insertEnclosingFunction": false, "files.autoSaveDelay": 500, "liveServer.settings.CustomBrowser": "chrome", "liveServer.settings.host": "localhost", "liveServer.settings.fullReload": true, "workbench.editor.enablePreview": false, "workbench.colorTheme": "Andromeda Bordered" } ``` ## 總結 以上簡單分享,希望對您有幫助!

增加開發者生產力:19 個簡單好用的 VScode 外掛

[VS Code](https://code.visualstudio.com/) 是一款免費、跨平台、開源的程式碼編輯器,近年來成為開發者最熱門的選擇。 在本文中,我整理了一些最有用的外掛,您可以使用它們來提高工作效率。 原文出處:https://dev.to/madza/19-vs-code-extensions-to-boost-your-productivity-4npo --- ### 1\. [Swimm](https://go.swimm.io/ide-plugin?utm_source=Hashnode&utm_medium=paid_influencer&utm_campaign=launch_may&utm_content=madza_dev) 使用 Swimm 的富文本編輯器建立文件。記錄跨越多個文件和存儲庫的複雜流程,其中包含與程式碼交互並在您進行更改時自動更新的豐富內容。 在本地驗證和更新文件,並將其作為 CI 工作流的一部分,自動修復簡單的錯誤,並且僅在發生重大更改時提醒您。 在正確的時間找到正確的文件——就在相關程式碼旁邊。當您看到一個 wave 時,這意味著存在與該特定程式碼部分相關的文件。 ![使用 Swimm 建立內部文件](https://storage.googleapis.com/swimmio-ide/assets/doc%20creation.png) ### 2\. [GitLens](https://marketplace.visualstudio.com/items?itemName=eamodio.gitlens) 借助 GitLens,開發人員可以通過提供有關 Git 存儲庫的高級可視化和訊息,更好地了解其程式碼庫的歷史、作者身份和更改。 GitLens 還提供了一組豐富的自定義選項,以及內聯責備註釋、提交和差異詳細訊息,甚至無需離開編輯器即可查看和編輯提交訊息的能力。 ![提交圖](https://raw.githubusercontent.com/gitkraken/vscode-gitlens/main/images/docs/commit-graph-illustrated.png) ### 3\. [Thunder Client](https://marketplace.visualstudio.com/items?itemName=rangav.vscode-thunder-client) Thunder Client 是用於 Visual Studio Code 的輕量級 Rest API 客戶端擴展,具有簡單易用的 UI。 支持集合和環境變數和 GraphQL 查詢,以及使用基於 GUI 的界面進行無腳本測試。 所有請求的資料都本地保存在您的設備上。 ![迅雷客戶端](https://github.com/rangav/thunder-client-support/blob/master/images/thunder-client-v2.png?raw=true) ### 4\. [Tabnine](https://marketplace.visualstudio.com/items?itemName=TabNine.tabnine-vscode) Tabnine 是一個 AI 程式碼助手,可以通過在所有最流行的編碼語言和 IDE 中實時完成程式碼來提高您的開發速度。 Tabnine 由多種語言專用的機器學習模型提供支持,這些模型是在程式碼上從頭開始進行預訓練的。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1683725176305/71c6f916-5dd6-475a-ac87-066bc301d3e3.gif) ### 5\. [Remote-SSH](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-ssh) Remote - SSH 擴展允許您使用任何帶有 SSH 伺服器的遠程機器作為您的開發環境。 無需在本地計算機上安裝源程式碼即可獲得這些好處,因為該擴展程序直接在遠程計算機上執行命令和其他擴展程序。 您可以打開遠程計算機上的任何文件夾並使用它,就像文件夾在您的計算機上一樣。 ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/psfddazji4zk1nfgcbrg.png) ### 6\. [Docker](https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-docker) Docker 擴展使從 Visual Studio Code 建置、管理和部署容器化應用程式變得容易。 它還提供了對容器內 Node.js、Python 和 .NET 的一鍵式除錯。 ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kifgjwnunn9ynmr2odcf.png) ### 7\. [Git History](https://marketplace.visualstudio.com/items?itemName=donjayamanne.githistory) 使用此擴展,用戶可以輕鬆瀏覽提交歷史記錄、檢查文件更改並比較程式碼的不同版本。 該擴展提供了一個 GUI,可以在時間軸中顯示提交歷史記錄。每個提交都與其提交訊息、作者、日期和時間一起顯示。 用戶還可以查看與每個提交關聯的分支和標籤名稱。 ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y7us7mebno5di3f7lp1l.png) ### 8\. [Markdown All in One](https://marketplace.visualstudio.com/items?itemName=yzhang.markdown-all-in-one) 對於在 VS Code 中使用大量 Markdown 的任何人來說,這是一個有用的工具。它使建立和編輯 Markdown 文件變得更加容易和快速,幫助您提高生產力和效率。 這些功能包括語法突出顯示、程式碼塊格式化、目錄、預覽模式、表情符號支持、鍵盤快捷鍵等等。 ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8f1ygmrmzd1ifz2q2pfq.png) ### 9\. [Regex Previewer](https://marketplace.visualstudio.com/items?itemName=chrmarti.regex) 該擴展在並排文件中顯示當前正則表達式的匹配項。這可以使用 Ctrl+Alt+M 打開/關閉。 可以通過狀態欄條目加入全局選項和多行選項,以便使用並排文件進行評估。當並排文件有多個匹配示例時,這會很有用。 ![執行中的正則表達式預覽器](https://github.com/chrmarti/vscode-regex/raw/main/images/in_action.gif) ### 10\. [Better Comments](https://marketplace.visualstudio.com/items?itemName=aaron-bond.better-comments) 使用此擴展,您將能夠將註釋分類為提醒、查詢、TODO、突出顯示等。 註釋掉的程式碼也可以設置樣式以明確程式碼不應該存在。您可以在設置中指定您想要的任何其他評論樣式。 ![無法為 Python 使用 vs 程式碼“更好的評論擴展”- 堆棧溢出](https://i.stack.imgur.com/MFQJN.png) ### 11\. [Bookmarks](https://marketplace.visualstudio.com/items?itemName=alefragnani.Bookmarks) 書籤擴展可幫助您導航程式碼,輕鬆快速地在重要位置之間移動。 不再需要搜尋程式碼。它還支持一組選擇命令,允許您選擇書籤行和書籤行之間的區域。它對日誌文件分析非常有用。 ![切換](https://github.com/alefragnani/vscode-bookmarks/raw/HEAD/images/printscreen-toggle.png) ### 12\. [Project Manager](https://marketplace.visualstudio.com/items?itemName=alefragnani.project-manager) 專案管理器可幫助您輕鬆存取您的專案,無論它們位於何處。不要再錯過那些重要的專案了。 您可以定義您的專案(也稱為收藏夾),或選擇自動檢測 Git、Mercurial 或 SVN 存儲庫、VS 程式碼文件夾或任何其他文件夾。 此外,您還可以使用標籤來組織您的專案。 ![側欄](https://github.com/alefragnani/vscode-project-manager/raw/HEAD/images/vscode-project-manager-side-bar-tags.gif) ### 13\. [Code Spell Checker](https://marketplace.visualstudio.com/items?itemName=streetsidesoftware.code-spell-checker) 一個基本的拼寫檢查器,適用於程式碼和文件。 這個拼寫檢查器的目標是幫助捕獲常見的拼寫錯誤,同時保持較低的誤報率。 ![示例](https://raw.githubusercontent.com/streetsidesoftware/vscode-spell-checker/main/images/example.gif) ### 14\. [Image Optimizer](https://marketplace.visualstudio.com/items?itemName=MadsKristensen.ImageOptimizer) 向解決方案資源管理器中的任何文件夾和圖像加入右鍵單擊菜單,使您可以自動優化該文件夾中的所有 PNG、GIF 和 JPEG 文件。 只需右鍵單擊任何包含圖像的文件或文件夾,然後單擊其中一個圖像優化按鈕。 ![輸出窗口](https://github.com/madskristensen/ImageOptimizer/raw/master/art/output-window.png) ### 15\. [CSS Peek](https://marketplace.visualstudio.com/items?itemName=pranaygp.vscode-css-peek) 該擴展支持符號定義跟踪的所有正常功能,但它適用於 CSS 選擇器(類、ID 和 HTML 標記)。 您可以內聯加載 CSS 文件並在此處進行快速編輯,直接跳轉到 CSS 文件或在新編輯器中打開它或在懸停時顯示定義。 ![工作](https://github.com/pranaygp/vscode-css-peek/raw/master/readme/working.gif) ### 16\. [Placeholder Images](https://marketplace.visualstudio.com/items?itemName=JakeWilson.vscode-placeholder-images) 使用各種第 3 方服務(如 Unsplash、LoremFlickr 等)在 Visual Studio Code 中生成佔位符圖像並將其插入到 HTML 中。 您可以選擇圖像寬度、高度、文本和顏色,將生成的 IMG 標籤插入到您的 HTML 中或將其複製到剪貼板,或者將圖像 URL 插入到您的 HTML 中,複製到剪貼板,或在您的瀏覽器中打開它。 ![使用 placehold.it 生成佔位符圖像](https://github.com/Jakobud/vscode-placeholder-images/raw/master/images/example.gif) ### 17\. [Live Server](https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer) 具有實時瀏覽器重新加載功能的快速開發實時伺服器。從狀態欄單擊即可啟動或停止伺服器。 允許用戶建立可自定義的端口號,設置伺服器根目錄,並在設置中提供默認的瀏覽器配置選項。 ![實時伺服器演示 VSCode](https://github.com/ritwickdey/vscode-live-server/raw/HEAD/images/Screenshot/vscode-live-server-animated-demo.gif) ### 18\. [Peacock](https://marketplace.visualstudio.com/items?itemName=johnpapa.vscode-peacock) 使用 Peacock,您可以巧妙地更改 VS Code 工作區的顏色。 當你有多個 VS Code 實例、使用 VS Live Share 或使用 VS Code 的遠程功能,並且你想快速辨識你的編輯器時,這是理想選擇。 ![孔雀窗](https://raw.githubusercontent.com/johnpapa/vscode-peacock/main/resources/hero.png) ### 19\. [Polacode](https://marketplace.visualstudio.com/items?itemName=pnp.polacode) Polacode 是 VS Code 的擴展,它可以對你的程式碼進行截圖。 該擴展生成一個與源具有相同風格和主題的螢幕截圖。 ![用法](https://github.com/octref/polacode/raw/master/demo/usage.gif) --- 以上簡單分享,希望對您有幫助~

後端 JS 訓練一:第3課 ── 用 node 寫入檔案內容

## 課程目標 - 用 node 寫入檔案內容 ## 課程內容 來學習一下用 node 寫入檔案的方法 學會這方法,可以用 node 寫腳本處理工作上的文書瑣事 --- 建立 `write-my-name.js` 程式,裡面輸入 ``` var fs = require('fs'); const readline = require('readline').createInterface({ input: process.stdin, output: process.stdout }); readline.question('請問您的大名?\n', function (answer) { fs.writeFile('my-name.txt', answer, function (err) { console.log('儲存成功。'); process.exit(0); }); }); ``` 然後去終端機輸入 ``` node write-my-name.js ``` 你會看到終端機要求你輸入內容,接著會去更新文字檔內容! --- 第一段的 `readline` 模組,是處理 `輸入/輸出` 資訊的模組,後面要呼叫 `createInterface` 並且用全域變數 `process` 來設定輸入、輸出來源 照做就好,背後意義不用細究,能用就好,有興趣自行 google `readline.question` 從終端機請求用戶輸入內容,`\n` 是換行字元,讓畫面更好看而已 注意 `readline.question` 後面還是把函式當參數傳,也就是依然採用「非同步程式設計」 很怪、很醜,對嗎?我同意,這語法設計實在意義不明 又不是在等待 AJAX 回應的同時,用戶可以先做別的事情 這邊就是要等用戶輸入完內容,程式往下走才有意義呀! 後面會教你如何改寫成「同步程式設計」,先照做就好 ## 課後作業 接續前一課的作業,現在來寫「新增」功能 請建立一個 `create.js` 檔案 使用者輸入 `node create.js` 之後,終端機會詢問 ``` 您要新增什麼待辦事項? ``` 使用者可以輸入內容,接著終端機會顯示 ``` 新增事項:XXXXXX ``` 打開 `todos.json` 查看,會看到剛剛輸入的項目出現在裡面 完成以上任務,你就完成這次的課程目標了!