🔍 搜尋結果:fetch

🔍 搜尋結果:fetch

深入探討 Javascript 函數式編程

[訂閱我的程式設計 YouTube 頻道](https://www.youtube.com/@alexmercedcoder) [訂閱我的資料 YouTube 頻道](https://www.youtube.com/@alexmerceddata) 函數式程式設計 (FP) 在軟體開發領域獲得了巨大的關注,JavaScript 開發人員越來越多地轉向這種範例,以更有效地解決問題並減少錯誤。從本質上講,函數式程式設計強調使用純函數、不變性以及柯里化、記憶化和 monad 等先進技術來建立更清晰、更可預測的程式碼。 在這篇文章中,我們將深入研究每個概念,以了解它們的工作原理以及它們在 JavaScript 開發中的重要性。我們將探索**純函數**的無副作用性質、用於維護狀態可預測性的**不變性**、用於增強函數重用和組合的**柯里化**、用於優化性能的**記憶化**以及用於以函數式風格處理副作用的**monad** 。 無論您是函數式程式設計的新手,還是希望加深對其在 JavaScript 中的應用的理解,這篇文章都將為您提供堅實的基礎和實際範例,以便將這些原則整合到您的編碼實踐中。讓我們揭開這些概念的神秘面紗,看看它們如何改變您編寫 JavaScript 程式碼的方式。 1. 純函數 ------ **純函數**是一種函數,在給定相同的輸入的情況下,將始終返回相同的輸出,並且不會導致任何可觀察到的副作用。這個概念在函數式程式設計中至關重要,因為它允許開發人員編寫更可預測和可測試的程式碼。 ### 在 JavaScript 中使用純函數的好處: - **可預測性:**由於純函數不依賴或修改其範圍之外的資料狀態,因此它們更容易推理和除錯。 - **可重複使用性:**純函數可以在應用程式的不同部分重複使用,而無需考慮外部上下文。 - **可測試性:**沒有隱藏狀態或副作用,純函數很容易測試;輸入和輸出是您需要考慮的全部。 ### JavaScript 中純函數的範例: 考慮一個簡單的函數來計算矩形的面積: ``` function rectangleArea(length, width) { return length * width; } ``` 這個函數是純粹的,因為它總是使用相同的參數來傳回相同的結果,而且它不會修改任何外部狀態或產生副作用。 ### 常見陷阱以及如何避免它們: 雖然純函數提供了許多好處,但開發人員在嘗試將它們整合到與資料庫、外部服務或全域狀態互動的應用程式時可能會面臨挑戰。以下是保持純度的一些技巧: - **避免副作用:**不要修改函數內的任何外部變數或物件。 - **本機處理狀態:**如果您的函數需要存取應用程式狀態,請考慮將狀態作為參數傳遞並傳回新狀態而不修改原始狀態。 透過理解和實現純函數,開發人員可以在充分利用 JavaScript 中函數式程式設計的全部功能方面邁出重要一步。 2. 不變性 ------ **不變性**是指資料建立後永不更改的原則。您無需修改現有物件,而是建立一個包含所需變更的新物件。這是函數式程式設計的基石,因為它有助於防止副作用並在應用程式的整個生命週期中保持資料的完整性。 ### JavaScript 如何處理不變性: 預設情況下,JavaScript 物件和陣列是可變的,這表示在需要時必須注意強制執行不變性。但是,有幾種技術和工具可以提供幫助: - **使用`const` :**雖然`const`不會使變數變得不可變,但它可以防止將變數辨識碼重新指派給新值,這是邁向不變性的一步。 - **Object.freeze():**此方法可以透過防止向物件新增屬性和修改現有屬性來使物件不可變。 - **陣列和物件的擴展語法:**使用擴展語法可以幫助建立新的陣列或物件,同時合併現有陣列或物件的元素或屬性,而無需修改原始陣列或物件。 ### 確保 JavaScript 中資料不變性的技術: 1. **寫入時複製:**始終建立一個新的物件或陣列,而不是修改現有的物件或陣列。例如: ``` const original = { a: 1, b: 2 }; const modified = { ...original, b: 3 }; // 'original' is not changed ``` 2. **使用函式庫:**像 Immutable.js 這樣的函式庫提供了高度最佳化的持久不可變資料結構,可以簡化不變性的實作。 ### 幫助實施不變性的函式庫: - **Immutable.js:**提供一系列本質上不可變的資料結構。 - **immer:**允許您透過使用臨時草稿狀態並套用變更來產生新的不可變狀態,以更方便的方式處理不可變狀態。 透過將不變性整合到 JavaScript 專案中,您可以增強資料完整性、提高應用程式效能(透過減少防禦性複製的需求)並提高程式碼的可預測性。它完全符合函數式程式設計的原則,從而產生更乾淨、更健壯的軟體。 3.柯里化 ----- **柯里化**是函數式程式設計中的一種變革性技術,其中具有多個參數的函數被轉換為一系列函數,每個函數採用一個參數。這種方法不僅使您的函數更加模組化,而且還增強了程式碼的可重複使用性和可組合性。 ### JavaScript 柯里化的實際用途: 柯里化允許建立高階函數,這些函數可以在應用程式的不同點使用不同的參數進行自訂和重複使用。它特別適用於: - **事件處理:**建立針對特定事件自訂的部分應用函數,但重複使用通用處理程序邏輯。 - **API 呼叫:**使用預定義參數(例如 API 金鑰或使用者 ID)設定函數,這些參數可以在不同的呼叫中重複使用。 ### 說明柯里化的逐步範例: 考慮一個簡單的函數來加兩個數字: ``` function add(a, b) { return a + b; } // Curried version of the add function function curriedAdd(a) { return function(b) { return a + b; }; } const addFive = curriedAdd(5); console.log(addFive(3)); // Outputs: 8 ``` 此範例展示了柯里化如何將簡單的加法函數轉變為更通用和可重複使用的函數。 ### 柯里化與部分應用: 雖然柯里化和部分應用都涉及將函數分解為更簡單、更具體的函數,但它們並不相同: - **柯里化(Currying):**將具有多個參數的函數轉換為一系列巢狀函數,每個函數只接受一個參數。 - **部分應用:**涉及透過預先填充一些參數來建立具有較少參數的函數。 這兩種技術在函數式程式設計中都很有價值,可以用來簡化複雜的函數簽名並提高程式碼模組化。 透過利用柯里化,開發人員可以增強函數的可重複使用性和組合性,從而在 JavaScript 專案中產生更清晰、更易於維護的程式碼。 4. 記憶 ----- **記憶化**是函數式程式設計中使用的最佳化技術,透過儲存昂貴的函數呼叫的結果並在相同的輸入再次發生時返回快取的結果來加速電腦程式。它在 JavaScript 中對於優化涉及繁重計算任務的應用程式的效能特別有用。 ### 為什麼記憶化在 JavaScript 很重要: - **效率:**減少使用相同參數重複呼叫函數所需的計算次數。 - **效能:**透過快取耗時操作的結果來提高應用程式回應能力。 - **可擴展性:**透過最小化計算開銷來幫助管理更大的資料集或更複雜的演算法。 ### 實現記憶化:範例和常用方法: 以下是 JavaScript 中記憶函數的基本範例: ``` function memoize(fn) { const cache = {}; return function(...args) { const key = args.toString(); if (!cache[key]) { cache[key] = fn.apply(this, args); } return cache[key]; }; } const factorial = memoize(function(x) { if (x === 0) { return 1; } else { return x * factorial(x - 1); } }); console.log(factorial(5)); // Calculates and caches the result console.log(factorial(5)); // Returns the cached result ``` 此範例示範了記憶化如何快取階乘計算的結果,從而顯著減少重複呼叫的計算時間。 ### 記憶化的優點和潛在缺點: #### 好處: - 顯著減少重複操作的處理時間。 - 透過避免冗餘計算來提高應用程式效率。 - 易於用高階函數實現。 #### 缺點: - 由於快取而增加記憶體使用量。 - 不適合具有不確定性輸出的函數或具有副作用的函數。 透過理解和實現記憶化,開發人員可以優化他們的 JavaScript 應用程式,使其更快、更有效率。然而,重要的是要考慮額外記憶體使用方面的權衡,並確保僅在能夠提供明顯好處的地方應用記憶化。 5. 單子 ----- **Monad**是函數式程式設計中使用的抽象資料類型,用於處理副作用,同時保持純函數原則。它們將行為和邏輯封裝在靈活的可連結結構中,允許順序操作,同時保持函數的純淨。 ### Monad 簡介及其在 FP 中的意義: Monad 提供了一個以受控方式處理副作用(如 IO、狀態、異常等)的框架,有助於保持功能的純度和可組合性。在 JavaScript 中,Promise 是一個常見的一元結構範例,可以乾淨且有效率地管理非同步操作。 ### JavaScript 中 Monad 的範例: - **Promises:**透過封裝待處理操作、成功值或錯誤來處理非同步操作,允許方法連結(如`.then()`和`.catch()` ): ``` new Promise((resolve, reject) => { setTimeout(() => resolve("Data fetched"), 1000); }) .then(data => console.log(data)) .catch(error => console.error(error)); ``` - **Maybe Monad:**透過封裝可能存在或不存在的值來幫助處理 null 或未定義的錯誤: ``` function Maybe(value) { this.value = value; } Maybe.prototype.bind = function(transform) { return this.value == null ? this : new Maybe(transform(this.value)); }; Maybe.prototype.toString = function() { return `Maybe(${this.value})`; }; const result = new Maybe("Hello, world!").bind(value => value.toUpperCase()); console.log(result.toString()); // Outputs: Maybe(HELLO, WORLD!) ``` ### Monad 定律與結構: Monad 必須遵循三個核心定律——同一性、關聯性和單位——以確保它們的行為可預測: - **同一性:**直接應用函數或透過 monad 傳遞函數應該會產生相同的結果。 - **關聯性:**執行操作的順序(連結)不影響結果。 - **單位:**一個值必須能夠被提升為一個單子而不改變其行為。 理解這些定律對於在函數式程式設計中有效地實現或利用 monad 至關重要。 ### Monad 如何管理副作用並保持功能純度: 透過封裝副作用,monad 允許開發人員保持程式碼庫的其餘部分純淨,從而更易於理解和維護。它們使副作用可預測和可管理,這對於維護狀態一致性和錯誤處理可能變得具有挑戰性的大型應用程式至關重要。 透過利用 monad,開發人員可以增強 JavaScript 應用程式的功能,確保它們以功能性的方式處理副作用,從而提高程式碼的可靠性和可維護性。 6. 這些概念如何相互關聯 ------------- 純函數、不變性、柯里化、記憶化和 monad 的概念不僅僅是單獨的元素,而是增強 JavaScript 應用程式的健全性和可維護性的互連工具。以下是他們如何共同創造一個有凝聚力的函數式程式設計環境。 ### 建立功能協同: - **純函數與不變性:**純函數確保函數沒有副作用,並為相同的輸入傳回相同的輸出,並透過防止資料意外變更的不變性來補充。它們共同確保了可預測且穩定的程式碼庫。 - **柯里化和記憶化:**柯里化允許將函數分解為更簡單的單參數函數,這些函數更易於管理和記憶。然後可以將記憶化應用於這些柯里化函數以緩存其結果,透過避免重複計算來優化應用程式的效能。 - **Monad 和純函數:** Monad 有助於以受控方式管理副作用,這使得純函數即使在處理 I/O 或狀態轉換等操作時也能保持純淨。這種副作用的封裝保留了功能架構的完整性。 ### 範例:一個小型功能模組: 讓我們考慮一個將這些概念結合在一起的實際範例。假設我們正在建立一個簡單的用戶註冊模組: ``` // A pure function to validate user input const validateInput = input => input.trim() !== ''; // A curried function for creating a user object const createUser = name => ({ id: Date.now(), name }); // Memoizing the createUser function to avoid redundant operations const memoizedCreateUser = memoize(createUser); // A monad for handling potential null values in user input const getUser = input => new Maybe(input).bind(validateInput); // Example usage const input = getUser(' John Doe '); const user = input.bind(memoizedCreateUser); console.log(user.toString()); // Outputs user details or empty Maybe ``` 在此範例中, `validateInput`是確保輸入有效性的純函數。 `createUser`是一個柯里化和記憶化的函數,針對效能進行了最佳化,而`getUser`使用 monad 來安全地處理潛在的 null 值。 結論: --- 理解和整合這些函數式程式設計概念可以顯著提高 JavaScript 程式碼的品質和可維護性。透過同時使用純函數、不變性、柯里化、記憶化和 monad,開發人員可以建立更可靠、更有效率、更乾淨的應用程式。 透過採用這些相互關聯的原則,JavaScript 開發人員可以充分利用函數式程式設計的潛力來編寫更好、更永續的程式碼。 --- 原文出處:https://dev.to/alexmercedcoder/deep-dive-into-functional-programming-in-javascript-851

🚀 21 個將你的開發技能帶上月球的工具 🌝

我見過數百種人工智慧工具,其中許多正在改變世界。 作為開發人員,總是有很多事情需要學習,因此專注於節省時間來處理重要的事情非常重要。 我將介紹 21 個供開發人員使用的工具,它們可以讓您的生活更輕鬆,特別是在開發人員體驗方面。 相信我,這份清單會讓你大吃一驚! 我們開始做吧。 --- 1. [Taipy](https://github.com/Avaiga/taipy) - 將資料和人工智慧演算法整合到生產就緒的 Web 應用程式中。 ---------------------------------------------------------------------------- ![打字](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wd10iiofzmt4or4db6ej.png) Taipy 是一個開源 Python 庫,可用於輕鬆的端到端應用程式開發,具有假設分析、智慧管道執行、內建調度和部署工具。 我相信你們大多數人都不明白 Taipy 用於為基於 Python 的應用程式建立 GUI 介面並改進資料流管理。 關鍵是性能,而 Taipy 是最佳選擇。 雖然 Streamlit 是一種流行的工具,但在處理大型資料集時,其效能可能會顯著下降,這使得它在生產級使用上不切實際。 另一方面,Taipy 在不犧牲性能的情況下提供了簡單性和易用性。透過嘗試 Taipy,您將親身體驗其用戶友好的介面和高效的資料處理。 ![大資料支持](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xnvk0tozn0lgj083rzcb.gif) Taipy 有許多整合選項,可以輕鬆地與領先的資料平台連接。 ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7yv31uir3erina587zp8.png) 開始使用以下命令。 ``` pip install taipy ``` 我們來談談最新的[Taipy v3.1 版本](https://docs.taipy.io/en/latest/relnotes/)。 最新版本使得在 Taipy 的多功能零件物件中可視化任何 HTML 或 Python 物件成為可能。 這意味著[Folium](https://python-visualization.github.io/folium/latest/) 、 [Bokeh](https://bokeh.org/) 、 [Vega-Altair](https://altair-viz.github.io/)和[Matplotlib](https://matplotlib.org/)等程式庫現在可用於視覺化。 這也帶來了對[Plotly python](https://plotly.com/python/)的原生支持,使繪製圖表變得更加容易。 他們還使用分散式運算提高了效能,但最好的部分是 Taipy,它的所有依賴項現在都與 Python 3.12 完全相容,因此您可以在使用 Taipy 進行專案的同時使用最新的工具和程式庫。 您可以閱讀[文件](https://docs.taipy.io/en/latest/)。 ![用例](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xdvnbejf9aivxmqsd3hx.png) 另一個有用的事情是,Taipy 團隊提供了一個名為[Taipy Studio](https://docs.taipy.io/en/latest/manuals/studio/)的 VSCode 擴充功能來加速 Taipy 應用程式的建置。 ![太皮工作室](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kc1umm5hcxes0ydbuspb.png) 您也可以使用 Taipy 雲端部署應用程式。 如果您想閱讀部落格來了解程式碼庫結構,您可以閱讀 HuggingFace[的使用 Taipy 在 Python 中為您的 LLM 建立 Web 介面](https://huggingface.co/blog/Alex1337/create-a-web-interface-for-your-llm-in-python)。 嘗試新技術通常很困難,但 Taipy 提供了[10 多個演示教程,](https://docs.taipy.io/en/release-3.1/gallery/)其中包含程式碼和適當的文件供您遵循。 ![示範](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4wigid2aokt6spkkoivr.png) 例如,一些演示範例和專案想法: - [即時污染儀表板](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/pollution_sensors/) 使用工廠周圍的感測器測量空氣品質的用例,展示 Taipy 儀表板流資料的能力。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-realtime-pollution)。 - [詐欺辨識](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/fraud_detection/) Taipy 應用程式可分析信用卡交易以偵測詐欺行為。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-fraud-detection)。 - [新冠儀表板](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/covid_dashboard/) 這使用 2020 年的 Covid 資料集。還有一個預測頁面來預測傷亡人數。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-covid-dashboard)。 - [建立 LLM 聊天機器人](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/chatbot/) 該演示展示了 Taipy 使最終用戶能夠使用 LLM 執行推理的能力。在這裡,我們使用 GPT-3 建立一個聊天機器人,並將對話顯示在互動式聊天介面中。您可以輕鬆更改程式碼以使用任何其他 API 或模型。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-chatbot)。 - [即時人臉辨識](https://docs.taipy.io/en/release-3.0/knowledge_base/demos/face_recognition/) 該演示將人臉辨識無縫整合到我們的平台中,使用網路攝影機提供使用者友好的即時人臉偵測體驗。檢查[GitHub 儲存庫](https://github.com/Avaiga/demo-face-recognition)。 這些用例非常驚人,所以一定要檢查一下。 Taipy 在 GitHub 上有 8.2k+ Stars,並且處於`v3.1`版本,因此它們正在不斷改進。 {% cta https://github.com/Avaiga/taipy %} Star Taipy ⭐️ {% endcta %} --- 2. [DevToys](https://github.com/DevToys-app/DevToys) - 開發者的瑞士軍刀。 ---------------------------------------------------------------- ![開發玩具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7zfl1wjr01fdvca6wxbi.png) DevToys 協助完成日常開發任務,例如格式化 JSON、比較文字和測試 RegExp。 這樣,就無需使用不可信的網站來處理您的資料執行簡單的任務。透過智慧型偵測,DevToys 可以偵測用於複製到 Windows 剪貼簿的資料的最佳工具。 緊湊的覆蓋範圍讓您可以保持應用程式較小並位於其他視窗之上。最好的部分是可以同時使用應用程式的多個實例。 我可以肯定地說,開發人員甚至不知道這個很棒的專案。 最後是一款專為 Windows 生態系統設計的軟體。哈哈! ![工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i7wd60jsgdb5tx2t2adi.png) 他們提供的一些工具是: > 轉換器 - JSON &lt;&gt; YAML - 時間戳 - 數基數 - 規劃任務解析器 ![轉換器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g8x784fx53x6ia02zal0.png) > 編碼器/解碼器 - 超文本標記語言 - 網址 - Base64 文字與圖片 - 壓縮包 - 智威湯遜解碼器 ![編碼器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/73ts4x1vtcy4yswsmytw.png) > 格式化程式 - JSON - SQL - XML ![XML](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e5dc8ko2baywta82ymq5.png) > 發電機 - 哈希(MD5、SHA1、SHA256、SHA512) - UUID 1 和 4 - 洛雷姆·伊普蘇姆 - 校驗和 ![發電機](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cwsq8xig6jf69wr99iuv.png) > 文字 - 逃脫/逃脫 - 檢驗員和箱子轉換器 - 正規表示式測試器 - 文字比較 - XML驗證器 - 降價預覽 ![MD預覽](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vcbkse1i5324qg3xu1yd.png) ![文字差異](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hlqqib4fcjimc03pdrwr.png) > 形象的 - 色盲模擬器 - 顏色選擇器和對比度 - PNG / JPEG 壓縮器 - 影像轉換器 ![圖形工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/631upekcqzh62xyrdjwt.png) 我不了解你,但我不會錯過這個! 您可以閱讀[如何執行 DevToys](https://github.com/DevToys-app/DevToys?tab=readme-ov-file#how-to-run-devtoys) 。 關於許可證的註解。 DevToys 使用的授權允許將應用程式作為試用軟體或共享軟體重新分發而無需進行任何更改。然而,作者 Etienne BAUDOUX 和 BenjaminT 不希望你這樣做。如果您認為自己有充分的理由這樣做,請先與我們聯絡討論。 他們在 GitHub 上有 23k Stars,並且使用 C#。 {% cta https://github.com/DevToys-app/DevToys %} 明星 DevToys ⭐️ {% endcta %} --- 3. [Pieces](https://github.com/pieces-app) - 您的工作流程副駕駛。 ------------------------------------------------------- ![件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qf2qgqtpv78fxw5guqm5.png) Pieces 是一款支援人工智慧的生產力工具,旨在透過智慧程式碼片段管理、情境化副駕駛互動和主動呈現有用材料來幫助開發人員管理混亂的工作流程。 它最大限度地減少了上下文切換、簡化了工作流程並提升了整體開發體驗,同時透過完全離線的 AI 方法維護了工作的隱私和安全性。太棒了:D ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2ro3rcwnqp4qrmv5e8s.png) 它與您最喜歡的工具無縫集成,以簡化、理解和提升您的編碼流程。 它具有比表面上看到的更令人興奮的功能。 - 它可以透過閃電般快速的搜尋體驗找到您需要的材料,讓您根據您的喜好透過自然語言、程式碼、標籤和其他語義進行查詢。可以放心地說“您的個人離線谷歌”。 - Pieces 使用 OCR 和 Edge-ML 升級螢幕截圖,以提取程式碼並修復無效字元。因此,您可以獲得極其準確的程式碼提取和深度元資料豐富。 您可以查看 Pieces 可用[功能的完整清單](https://pieces.app/features)。 您可以閱讀[文件](https://docs.pieces.app/)並存取[網站](https://pieces.app/)。 他們為 Pieces OS 用戶端提供了一系列 SDK 選項,包括[TypeScript](https://github.com/pieces-app/pieces-os-client-sdk-for-typescript) 、 [Kotlin](https://github.com/pieces-app/pieces-os-client-sdk-for-kotlin) 、 [Python](https://github.com/pieces-app/pieces-os-client-sdk-for-python)和[Dart](https://github.com/pieces-app/pieces-os-client-sdk-for-dart) 。 就開源流行度而言,他們仍然是新的,但他們的社群是迄今為止我見過的最好的社群之一。加入他們,成為 Pieces 的一部分! {% cta https://github.com/pieces-app/ %} 星星碎片 ⭐️ {% endcta %} --- 4. [Infisical-](https://github.com/Infisical/infisical)秘密管理平台。 -------------------------------------------------------------- ![內部的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jrolzjdnkky1r694h9av.png) Infisical 是一個開源秘密管理平台,團隊可以用它來集中 API 金鑰、資料庫憑證和設定等秘密。 他們讓每個人(而不僅僅是安全團隊)都可以更輕鬆地進行秘密管理,這意味著從頭開始重新設計整個開發人員體驗。 就我個人而言,我不介意使用 .env 文件,因為我並不特別謹慎。不過,您可以閱讀[立即停止使用 .env 檔案!](https://dev.to/gregorygaines/stop-using-env-files-now-kp0)由格雷戈里來理解。 他們提供了四種 SDK,分別用於<a href="">Node.js</a> 、 <a href="">Python</a> 、 <a href="">Java</a>和<a href="">.Net</a> 。您可以自行託管或使用他們的雲端。 開始使用以下 npm 指令。 ``` npm install @infisical/sdk ``` 這是使用入門 (Node.js SDK) 的方法。 ``` import { InfisicalClient, LogLevel } from "@infisical/sdk"; const client = new InfisicalClient({ clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", logLevel: LogLevel.Error }); const secrets = await client.listSecrets({ environment: "dev", projectId: "PROJECT_ID", path: "/foo/bar/", includeImports: false }); ``` ![內部](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h3eu288l470du91b66pd.png) Infisical 還提供了一組工具來自動防止 git 歷史記錄的秘密洩露。可以使用預提交掛鉤或透過與 GitHub 等平台直接整合在 Infisical CLI 層級上設定此功能。 您可以閱讀[文件](https://infisical.com/docs/documentation/getting-started/introduction)並檢查如何[安裝 CLI](https://infisical.com/docs/cli/overview) ,這是使用它的最佳方式。 Infisical 還可用於將機密注入 Kubernetes 叢集和自動部署,以便應用程式使用最新的機密。有很多整合選項可用。 ![內部](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5x0tvt5ycaiqhggv6wml.png) 在使用整個原始程式碼之前一定要檢查他們的[許可證](https://github.com/Infisical/infisical/blob/main/LICENSE),因為他們有一些受 MIT Expat 保護的企業級程式碼,但不用擔心,大部分程式碼都是免費使用的。 他們在 GitHub 上擁有超過 11k 顆星星,並且發布了超過 125 個版本,因此他們正在不斷發展。另外,Infiscial CLI 的安裝次數超過 540 萬次,因此非常值得信賴。 {% cta https://github.com/Infisical/infisical %} 明星 Infisical ⭐️ {% endcta %} --- 5. [Mintlify](https://github.com/mintlify/writer) - 在建置時出現的文件。 -------------------------------------------------------------- ![精簡](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gvk07kmn8p48cpssogov.png) Mintlify 是一款由人工智慧驅動的文件編寫器,您只需 1 秒鐘即可編寫程式碼文件 :D 幾個月前我發現了 Mintlify,從那時起我就一直是它的粉絲。我見過很多公司使用它,甚至我使用我的商務電子郵件產生了完整的文件,結果證明這是非常簡單和體面的。如果您需要詳細的文件,Mintlify 就是解決方案。 主要用例是根據我們將在此處討論的程式碼產生文件。當您編寫程式碼時,它會自動記錄程式碼,以便其他人更容易跟上。 您可以安裝[VSCode 擴充功能](https://marketplace.visualstudio.com/items?itemName=mintlify.document)或將其安裝在[IntelliJ](https://plugins.jetbrains.com/plugin/18606-mintlify-doc-writer)上。 您只需突出顯示程式碼或將遊標放在要記錄的行上。然後點選「編寫文件」按鈕(或按 ⌘ + 。) 您可以閱讀[文件](https://github.com/mintlify/writer?tab=readme-ov-file#%EF%B8%8F-mintlify-writer)和[安全指南](https://writer.mintlify.com/security)。 如果您更喜歡教程,那麼您可以觀看[Mintlify 的工作原理](https://www.loom.com/embed/3dbfcd7e0e1b47519d957746e05bf0f4)。它支援 10 多種程式語言,並支援許多文件字串格式,例如 JSDoc、reST、NumPy 等。 順便說一句,他們的網站連結是[writer.mintlify.com](https://writer.mintlify.com/) ;回購協議中目前的似乎是錯誤的。 Mintlify 是一個方便的工具,用於記錄程式碼,這是每個開發人員都應該做的事情。它使其他人更容易有效地理解您的程式碼。 它在 GitHub 上有大約 2.5k 顆星,基於 TypeScript 建置,受到許多開發人員的喜愛。 {% cta https://github.com/mintlify/writer %} Star Mintlify ⭐️ {% endcta %} --- 6. [Replexica](https://github.com/replexica/replexica) - 用於 React 的 AI 支援的 i18n 工具包。 ------------------------------------------------------------------------------------ ![反射](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/htgshukxy927iy37ui33.png) 在地化方面的困難是真實存在的,因此人工智慧的幫助絕對是一個很酷的概念。 Replexica 是 React 的 i18n 工具包,可快速發布多語言應用程式。它不需要將文字提取到 JSON 檔案中,並使用 AI 支援的 API 進行內容處理。 它有以下兩個部分: 1. Replexica Compiler - React 的開源編譯器插件。 2. Replexica API - 雲端中的 i18n API,使用 LLM 執行翻譯。 (基於使用情況,它有免費套餐) 支援的一些 i18n 格式包括: 1. 無 JSON 的 Replexica 編譯器格式。 2. Markdown 內容的 .md 檔案。 3. 基於舊版 JSON 和 YAML 的格式。 當他們達到 500 星時,他們也在 DEV 上發布了官方公告。我是第一批讀者之一(少於 3 個反應)。 它們涵蓋了很多內容,因此您應該閱讀 Max 的[《We Got 500 Stars What Next》](https://dev.to/maxprilutskiy/we-got-500-github-stars-whats-next-2njc) 。 為了給出 Replexica 背後的總體思路,這是基本 Next.js 應用程式所需的唯一更改,以使其支援多語言。 開始使用以下 npm 指令。 ``` // install pnpm add replexica @replexica/react @replexica/compiler // login to Replexica API. pnpm replexica auth --login ``` 您可以這樣使用它。 ``` // next.config.mjs // Import Replexica Compiler import replexica from '@replexica/compiler'; /** @type {import('next').NextConfig} */ const nextConfig = {}; // Define Replexica configuration /** @type {import('@replexica/compiler').ReplexicaConfig} */ const replexicaConfig = { locale: { source: 'en', targets: ['es'], }, }; // Wrap Next.js config with Replexica Compiler export default replexica.next( replexicaConfig, nextConfig, ); ``` 您可以閱讀如何[開始使用](https://github.com/replexica/replexica/blob/main/getting-started.md)以及清楚記錄的有關[幕後使用內容的](https://github.com/replexica/replexica?tab=readme-ov-file#whats-under-the-hood)內容。 Replexica 編譯器支援 Next.js App Router,Replexica API 支援英文🇺🇸和西班牙文🇪🇸。他們計劃接下來發布 Next.js Pages Router + 法語🇫🇷語言支援! 他們在 GitHub 上擁有 740 多個 Star,並且基於 TypeScript 建置。您應該密切關注該專案以獲得進一步進展! {% cta https://github.com/replexica/replexica %} Star Replexica ⭐️ {% endcta %} --- 7. [Flowise](https://github.com/FlowiseAI/Flowise) - 拖放 UI 來建立您的客製化 LLM 流程。 --------------------------------------------------------------------------- ![弗洛伊薩伊](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r5bp43nil764fhe4a05z.png) Flowise 是一款開源 UI 視覺化工具,用於建立客製化的 LLM 編排流程和 AI 代理程式。 開始使用以下 npm 指令。 ``` npm install -g flowise npx flowise start OR npx flowise start --FLOWISE_USERNAME=user --FLOWISE_PASSWORD=1234 ``` 這就是整合 API 的方式。 ``` import requests url = "/api/v1/prediction/:id" def query(payload): response = requests.post( url, json = payload ) return response.json() output = query({ question: "hello!" )} ``` ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ahk2ovjrpq1qk3r5pfot.png) 您可以閱讀[文件](https://docs.flowiseai.com/)。 ![流程化人工智慧](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trkltpn5lk1y1pte0smd.png) 雲端主機不可用,因此您必須使用這些[說明](https://github.com/FlowiseAI/Flowise?tab=readme-ov-file#-self-host)自行託管。 讓我們探討一些用例: - 假設您有一個網站(可以是商店、電子商務網站或部落格),並且您希望廢棄該網站的所有相關連結,並讓法學碩士回答您網站上的任何問題。您可以按照此[逐步教學](https://docs.flowiseai.com/use-cases/web-scrape-qna)來了解如何實現相同的目標。 ![刮刀](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e91sz2mga5wvc0x2hp2g.png) - 您還可以建立一個自訂工具,該工具將能夠呼叫 Webhook 端點並將必要的參數傳遞到 Webhook 主體中。請依照本[指南](https://docs.flowiseai.com/use-cases/webhook-tool)使用 Make.com 建立 Webhook 工作流程。 ![網路鉤子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ckyivo9dvue461jc9pv4.png) 還有許多其他用例,例如建立 SQL QnA 或與 API 互動。 FlowiseAI 在 GitHub 上擁有超過 27,500 個 Star,並擁有超過 10,000 個分叉,因此具有良好的整體比率。 {% cta https://github.com/FlowiseAI/Flowise %} 明星 Flowise ⭐️ {% endcta %} --- 8. [Hexo](https://github.com/hexojs/hexo) - 一個快速、簡單且功能強大的部落格框架。 --------------------------------------------------------------- ![六角形](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6vos07fyydiupqqplo2s.png) 大多數開發人員更喜歡自己的博客,如果您也是如此。 Hexo 可能是你不知道的工具。 Hexo 支援許多功能,例如超快的生成速度,支援 GitHub Flavored Markdown 和大多數 Octopress 插件,提供對 GitHub Pages、Heroku 等的一命令部署,以及可實現無限擴展性的強大 API 和數百個主題和插件。 這意味著您可以用 Markdown(或其他標記語言)編寫帖子,Hexo 在幾秒鐘內生成具有漂亮主題的靜態檔案。 開始使用以下 npm 指令。 ``` npm install hexo-cli -g ``` 您可以這樣使用它。 ``` // Setup your blog hexo init blog // Start the server hexo server // Create a new post hexo new "Hello Hexo" ``` 您可以閱讀[文件](https://hexo.io/docs/),查看 Hexo 提供的所有[400 多個外掛程式](https://hexo.io/plugins/)和[主題集](https://hexo.io/themes/)。據我所知,這些外掛程式支援廣泛的用例,例如 Hexo 的 Ansible 部署器外掛程式。 您可以查看有關在[Hexo 上編寫和組織內容的](https://www.youtube.com/watch?v=AIqBubK6ZLc&t=6s)YouTube 教學。 Hexo 在 GitHub 上擁有超過 38,000 顆星,並被 GitHub 上超過 125,000 名開發者使用。它們位於`v7`版本中,解壓縮後大小為`629 kB` 。 {% cta https://github.com/hexojs/hexo %} Star Hexo ⭐️ {% endcta %} --- 9.[螢幕截圖到程式碼](https://github.com/abi/screenshot-to-code)- 放入螢幕截圖並將其轉換為乾淨的程式碼。 --------------------------------------------------------------------------- ![截圖到程式碼](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5akiyz5telxqqsj32ftu.png) 這個開源專案廣泛流行,但許多開發人員仍然不了解它。它可以幫助您以 10 倍的速度建立使用者介面。 這是一個簡單的工具,可以使用 AI 將螢幕截圖、模型和 Figma 設計轉換為乾淨、實用的程式碼。 該應用程式有一個 React/Vite 前端和一個 FastAPI 後端。如果您想使用 Claude Sonnet 或獲得實驗視訊支持,您將需要一個能夠存取 GPT-4 Vision API 的 OpenAI API 金鑰或一個 Anthropic 金鑰。您可以閱讀[指南](https://github.com/abi/screenshot-to-code?tab=readme-ov-file#-getting-started)來開始。 您可以在託管版本上[即時試用](https://screenshottocode.com/),並觀看 wiki 上提供的[一系列演示影片](https://github.com/abi/screenshot-to-code/wiki/Screen-Recording-to-Code)。 他們在 GitHub 上擁有超過 47k 顆星星,並支援許多技術堆疊,例如 React 和 Vue,以及不錯的 AI 模型,例如 GPT-4 Vision、Claude 3 Sonnet 和 DALL-E 3。 {% cta https://github.com/abi/screenshot-to-code %} 將螢幕截圖轉為程式碼 ⭐️ {% endcta %} --- 10. [Appsmith](https://github.com/appsmithorg/appsmith) - 建立管理面板、內部工具和儀表板的平台。 ----------------------------------------------------------------------------- ![應用史密斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rt7s0r3wz2leec83cl17.png) 管理面板和儀表板是任何軟體創意(在大多數情況下)的一些常見部分,我嘗試從頭開始建立它,這會帶來很多痛苦和不必要的辛苦工作。 您可能已經看到組織建立了內部應用程式,例如儀表板、資料庫 GUI、管理面板、批准應用程式、客戶支援儀表板等,以幫助其團隊執行日常操作。正如我所說,Appsmith 是一個開源工具,可以實現這些內部應用程式的快速開發。 首先,請觀看這個[YouTube 影片](https://www.youtube.com/watch?v=NnaJdA1A11s),該影片在 100 秒內解釋了 Appsmith。 {% 嵌入 https://www.youtube.com/watch?v=NnaJdA1A11s %} 他們提供拖放小部件來建立 UI。 您可以使用 45 多個可自訂的小工具在幾分鐘內建立漂亮的響應式 UI,而無需編寫一行 HTML/CSS。尋找[小部件的完整清單](https://www.appsmith.com/widgets)。 ![按鈕點擊小工具](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqpnnslvsvjl4gifseon.png) ![驗證](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/489fly7tvknz2uv2mgei.png) Appsmith 幾乎可以在 GUI 上的小部件屬性、事件偵聽器、查詢和其他設定內的任何位置編寫 JavaScript 程式碼。 Appsmith 支援在`{{ }}`內編寫單行程式碼,並將括號之間編寫的任何內容解釋為 JavaScript 表達式。 ``` /*Filter the data array received from a query*/ {{ QueryName.data.filter((row) => row.id > 5 ) }} or {{ storeValue("userID", 42); console.log(appsmith.store.userID); showAlert("userID saved"); }} ``` 您需要使用立即呼叫函數表達式(IIFE)來編寫多行。 例如,無效程式碼和有效程式碼。 ``` // invalid code /*Call a query to fetch the results and filter the data*/ {{ const array = QueryName.data; const filterArray = array.filter((row) => row.id > 5); return filterArray; }} /* Check the selected option and return the value*/ {{ if (Dropdown.selectedOptionValue === "1") { return "Option 1"; } else { return "Option 2"; } }} // valid code /* Call a query and then manipulate its result */ {{ (function() { const array = QueryName.data; const filterArray = array.filter((row) => row.id > 5); return filterArray; })() }} /* Verify the selected option and return the value*/ {{ (function() { if (Dropdown.selectedOptionValue === "1") { return "Option 1"; } else { return "Option 2"; } })() }} ``` 您可以透過幾個簡單的步驟建立從簡單的 CRUD 應用程式到複雜的多步驟工作流程的任何內容: 1. 與資料庫或 API 整合。 Appsmith 支援最受歡迎的資料庫和 REST API。 2. 使用內建小工具建立您的應用程式佈局。 3. 在編輯器中的任何位置使用查詢和 JavaScript 來表達您的業務邏輯。 4. Appsmith 支援使用 Git 進行版本控制,以使用分支來協作建立應用程式來追蹤和回滾變更。部署應用程式並分享:) ![應用史密斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yltcrmuzwdoydrwyqjpp.png) 您可以閱讀[文件](https://docs.appsmith.com/)和[操作指南](https://docs.appsmith.com/connect-data/how-to-guides),例如如何將其連接到本機資料來源或\[如何與第三方工具整合\](與第三方工具整合)。 您可以自行託管或使用雲端。他們還提供[20 多個模板](https://www.appsmith.com/templates),以便您可以快速入門。一些有用的是: - [維修訂單管理](https://www.appsmith.com/template/Maintenance-Order-Management) - [加密即時追蹤器](https://www.appsmith.com/template/crypto-live-tracker) - [內容管理系統](https://www.appsmith.com/template/content-management-system) - [WhatsApp 信使](https://www.appsmith.com/template/whatsapp-messenger) Appsmith 在 GitHub 上擁有超過 31,000 顆星,發布了 200 多個版本。 {% cta https://github.com/appsmithorg/appsmith %} Star Appsmith ⭐️ {% endcta %} --- 11. [BlockNote](https://github.com/TypeCellOS/BlockNote) - 基於區塊(Notion 樣式)且可擴充的富文本編輯器。 -------------------------------------------------------------------------------------- ![區塊註釋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eddx8cld0g492w3a8fjh.png) 人們常說,除非您正在學習新東西,否則不要重新發明輪子。 Blocknote 是開源的 Block 為基礎的 React 富文本編輯器。您可以輕鬆地將現代文字編輯體驗加入到您的應用程式中。 Blocknote 建構在 Prosemirror 和 Tiptap 之上。 它們有很多功能,如下所示。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h9kd6xnkg9fa5j29frot.png) ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ezuz7ywh6vefixmpeyzk.png) 您可以輕鬆自訂內建 UI 元件,或建立自訂區塊、內聯內容和樣式。如果您想更進一步,您可以使用額外的 Prosemirror 或 TipTap 外掛程式來擴充核心編輯器。 其他庫雖然功能強大,但通常具有相當陡峭的學習曲線,並且要求您自訂編輯器的每個細節。這可能需要數月的專門工作。 相反,BlockNote 只需最少的設定即可提供出色的體驗,包括現成的動畫 UI。 開始使用以下 npm 指令。 ``` npm install @blocknote/core @blocknote/react ``` 您可以這樣使用它。透過`useCreateBlockNote`鉤子,我們可以建立一個新的編輯器實例,然後使用`theBlockNoteView`元件來渲染它。 `@blocknote/react/style.css`也被匯入來新增編輯器的預設樣式和 BlockNote 匯出的 Inter 字體(可選)。 ``` import "@blocknote/core/fonts/inter.css"; import { BlockNoteView, useCreateBlockNote } from "@blocknote/react"; import "@blocknote/react/style.css"; export default function App() { // Creates a new editor instance. const editor = useCreateBlockNote(); // Renders the editor instance using a React component. return <BlockNoteView editor={editor} />; } ``` 您可以閱讀可用的[文件](https://www.blocknotejs.org/docs)和[ui 元件](https://www.blocknotejs.org/docs/ui-components)。 您應該嘗試一下,特別是因為它包含廣泛的功能,例如「斜線」選單、流暢的動畫以及建立即時協作應用程式的潛力。 ![削減](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0i7ob8nrhpl7r70k6527.png) 斜線選單 ![即時協作](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/id22qol6y0838zgwad3y.png) 即時協作 ![格式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d8maems8tfhtehw9lkol.png) 格式選單 他們還提供了[20 多個範例](https://www.blocknotejs.org/examples)以及預覽和程式碼,您可以使用它們來快速跟進。 ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4uillknk0ogkcvpula7b.png) Blocknote 在 GitHub 上擁有超過 5,000 顆星,並有超過 1,500 名開發者在使用。 {% cta https://github.com/TypeCellOS/BlockNote %} 星 BlockNote ⭐️ {% endcta %} --- 12. [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 在數小時內為您的產品提供 AI Copilot。 ------------------------------------------------------------------------------------- ![副駕駛套件](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。 CopilotKit 在 GitHub 上擁有超過 4,200 個星星,發布了 200 多個版本,這意味著它們正在不斷改進。 {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} --- 13.[自動完成](https://github.com/withfig/autocomplete)- IDE 風格的自動完成功能適用於您現有的終端和 shell。 ---------------------------------------------------------------------------------- ![自動完成](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8i8vcidsa023jf8r9382.png) [Fig](https://fig.io/?ref=github_autocomplete)讓命令列對個人來說更容易,對團隊來說更具協作性。 他們最受歡迎的產品是自動完成。當您鍵入時,Fig 會在現有終端機中彈出子命令、選項和上下文相關的參數。 最好的部分是您也可以將 Fig 的自動完成功能用於您自己的工具。以下是建立私人完成的方法: ``` import { ai } from "@fig/autocomplete-generators" ... generators: [ ai({ // the prompt prompt: "Generate a git commit message", // Send any relevant local context. message: async ({ executeShellCommand }) => { return executeShellCommand("git diff") }, //Turn each newline into a suggestion (can specify instead a `postProcess1 function if more flexibility is required) splitOn: "\n", }) ] ``` 您可以閱讀[Fig.io/docs](https://fig.io/docs/getting-started)了解如何開始。 他們在 GitHub 上有 24k+ Stars,這對於經常使用 shell 或終端機的開發人員來說非常有用。 {% cta https://github.com/withfig/autocomplete %} 星狀自動完成 ⭐️ {% endcta %} --- 14. [Tooljet](https://github.com/ToolJet/ToolJet) - 用於建立業務應用程式的低程式碼平台。 ---------------------------------------------------------------------- ![工具噴射器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xhipvjl2wnthjccgrpij.png) 我們都建立前端,但它通常非常複雜並且涉及很多因素。這樣可以省去很多麻煩。 ToolJet 是一個開源低程式碼框架,可以用最少的工程工作來建置和部署內部工具。 ToolJet 的拖放式前端建構器可讓您在幾分鐘內建立複雜的響應式前端。 您可以整合各種資料來源,包括PostgreSQL、MongoDB、Elasticsearch等資料庫;具有 OpenAPI 規範和 OAuth2 支援的 API 端點; SaaS 工具,例如 Stripe、Slack、Google Sheets、Airtable 和 Notion;以及 S3、GCS 和 Minio 等物件儲存服務來取得和寫入資料。一切 :) 這就是 Tooljet 的工作原理。 ![工具噴射器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r6vv09z7ioma1ce2ttei.png) 您可以在 ToolJet 中開發多步驟工作流程以自動化業務流程。除了建置和自動化工作流程之外,ToolJet 還可以在您的應用程式中輕鬆整合這些工作流程。 ![工作流程](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eh2vk3kih9fhck6okf67.png) 您可以閱讀此[快速入門指南](https://docs.tooljet.com/docs/getting-started/quickstart-guide),該指南向您展示如何使用 ToolJet 在幾分鐘內建立員工目錄應用程式。該應用程式將讓您透過漂亮的用戶介面追蹤和更新員工資訊。 查看可用[功能列表](https://github.com/ToolJet/ToolJet?tab=readme-ov-file#all-features),包括 45 多個內建響應式元件、50 多個資料來源等等。 您可以閱讀[文件](https://docs.tooljet.com/docs/)並查看[操作指南](https://docs.tooljet.com/docs/how-to/use-url-params-on-load)。 它們在 GitHub 上有 26k+ Stars,並且基於 JavaScript 建置。他們也獲得了 GitHub 的資助,從而建立了巨大的信任。 {% cta https://github.com/ToolJet/ToolJet %} Star ToolJet ⭐️ {% endcta %} --- 15. [Apitable](https://github.com/apitable/apitable) - 用於建立協作應用程式的 API 導向的低程式碼平台。 --------------------------------------------------------------------------------- ![有能力的](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58syhvpb2fn6hhlyrtst.png) APITable 是一個面向 API 的低程式碼平台,用於建立協作應用程式,並表示它比所有其他 Airtable 開源替代品都要好。 有很多很酷的功能,例如: - 即時協作。 ![即時協作](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58kpvpab2nj92421yvy3.gif) - 您可以產生自動表單。 ![形式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0jo084gg0cd9xiud3nz3.gif) - 無限的跨錶連結。 ![交叉表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jnvb9sdp3uqrcn55hwug.gif) - API 第一個面板。 ![API第一個面板](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7u48ue4rl0q41rhh6bif.gif) - 強大的行/列功能。 ![行列](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/apxqwp84awdbj7cdw5yu.gif) 您可以閱讀完整的[功能清單](https://github.com/apitable/apitable?tab=readme-ov-file#-features)。 您可以嘗試[apitable](https://aitable.ai/)並在 apitable 的[live Gitpod demo](https://gitpod.io/#https://github.com/apitable/apitable)中查看該專案的演示。 您也可以閱讀[安裝指南](https://github.com/apitable/apitable?tab=readme-ov-file#installation),在本機或雲端運算環境中安裝 APITable。 {% cta https://github.com/apitable/apitable %} Star Apitable ⭐️ {% endcta %} --- 16. [n8n](https://github.com/n8n-io/n8n) - 工作流程自動化工具。 ----------------------------------------------------- ![n8n](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4pqsc84nhgj0b9dhfaxo.png) n8n 是一個可擴展的工作流程自動化工具。透過公平程式碼分發模型,n8n 將始終擁有可見的原始程式碼,可用於自託管,並允許您加入自訂函數、邏輯和應用程式。 每個開發人員都想使用的工具。自動化是生產力和簡單性的關鍵。 ![n8n](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rxnp57kw5szbpj6mfs1p.png) n8n 基於節點的方法使其具有高度通用性,使您能夠將任何事物連接到任何事物。 有[400 多個集成選項](https://n8n.io/integrations),這幾乎是瘋狂的! 您可以看到所有[安裝](https://docs.n8n.io/choose-n8n/)選項,包括 Docker、npm 和自架。 開始使用以下命令。 ``` npx n8n ``` 此命令將下載啟動 n8n 所需的所有內容。然後,您可以透過開啟`http://localhost:5678`來存取 n8n 並開始建置工作流程。 在 YouTube 上觀看此[快速入門影片](https://www.youtube.com/watch?v=1MwSoB0gnM4)! {% 嵌入 https://www.youtube.com/watch?v=1MwSoB0gnM4 %} 您可以閱讀[文件](https://docs.n8n.io/)並閱讀本[指南](https://docs.n8n.io/try-it-out/),以便根據您的需求快速開始。 他們還提供初學者和中級[課程,](https://docs.n8n.io/courses/)以便輕鬆學習。 他們在 GitHub 上有 39k+ Stars,並提供兩個包供整體使用。 {% cta https://github.com/n8n-io/n8n %} 明星 n8n ⭐️ {% endcta %} --- 17. [DOMPurify](https://github.com/cure53/DOMPurify) - 一個僅限 DOM、超快、超級容忍 XSS 的 HTML 清理程式。 ---------------------------------------------------------------------------------------- ![DOM純化](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r846r2hmmw9d9wzvbocz.png) DOMPurify 是一款僅限 DOM、超快、超級容忍 XSS 的 HTML、MathML 和 SVG 清理工具。作為開發人員,我們的應用程式需要它來確保它們足夠安全。 DOMPurify 可以淨化 HTML 並防止 XSS 攻擊。 您可以向 DOMPurify 提供一個充滿髒 HTML 的字串,它將傳回一個包含乾淨 HTML 的字串(除非另有配置)。 DOMPurify 將刪除所有包含危險 HTML 的內容,從而防止 XSS 攻擊和其他惡意行為。這也太快了。 他們使用瀏覽器提供的技術並將其轉變為 XSS 過濾器。您的瀏覽器速度越快,DOMPurify 的速度就越快。 DOMPurify 使用 JavaScript 編寫,適用於所有現代瀏覽器(Safari (10+)、Opera (15+)、Edge、Firefox 和 Chrome - 以及幾乎所有使用 Blink、Gecko 或 WebKit 的其他瀏覽器)。它不會在 MSIE 或其他舊版瀏覽器上中斷。它根本什麼都不做。 開始使用以下 npm 指令。 ``` npm install dompurify npm install jsdom // or use the unminified development version <script type="text/javascript" src="src/purify.js"></script> ``` 您可以這樣使用它。 ``` const createDOMPurify = require('dompurify'); const { JSDOM } = require('jsdom'); const window = new JSDOM('').window; const DOMPurify = createDOMPurify(window); const clean = DOMPurify.sanitize('<b>hello there</b>'); ``` 如果您遇到問題,請參閱[文件](https://github.com/cure53/DOMPurify?tab=readme-ov-file#how-do-i-use-it)。他們已經記錄了使用腳本或在伺服器端執行它。 您可以看到一些 [純化樣品](https://github.com/cure53/DOMPurify?tab=readme-ov-file#some-purification-samples-please)並觀看[現場演示](https://cure53.de/purify)。 使用起來也非常簡單。 DOMPurify 於 2014 年 2 月啟動,同時版本已達 v3.1.0。 其中涉及到很多概念,我渴望探索它們。如果您有任何與此相關的令人興奮的事情,請告訴我。 我發現的另一個有用的替代方案是[validator.js](https://github.com/validatorjs/validator.js) 。 他們在 GitHub 上擁有超過 12,000 顆星,被超過 30 萬開發者使用,每週下載量超過 5,475,000 次,這使得他們非常可信。 {% cta https://github.com/cure53/DOMPurify %} 明星 DOMPurify ⭐️ {% endcta %} --- 18. [OpenDevin](https://github.com/OpenDevin/OpenDevin) - 更少的程式碼,更多的內容。 ----------------------------------------------------------------------- ![奧彭文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4on63bb02g4x4ny8gtcn.png) ![奧彭文](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l0yepod2rye2jk5r12dt.png) 這是一個開源專案,旨在複製 Devin,一名自主人工智慧軟體工程師,能夠執行複雜的工程任務並在軟體開發專案上與用戶積極協作。該計畫致力於透過開源社群的力量複製、增強和創新 Devin。 只是想讓你知道,這是在德文被介紹之前。 您可以閱讀帶有要求的[安裝說明](https://github.com/OpenDevin/OpenDevin?tab=readme-ov-file#installation)。 他們使用 LiteLLM,因此您可以使用任何基礎模型來執行 OpenDevin,包括 OpenAI、Claude 和 Gemini。 如果您想為 OpenDevin 做出貢獻,您可以查看 [演示](https://github.com/OpenDevin/OpenDevin/blob/main/README.md#opendevin-code-less-make-more)和[貢獻指南](https://github.com/OpenDevin/OpenDevin/blob/main/CONTRIBUTING.md)。 它在 GitHub 上擁有超過 10,700 個 Star,並且正在快速成長。 {% cta https://github.com/OpenDevin/OpenDevin %} 明星 OpenDevin ⭐️ {% endcta %} --- 19. [Amplification-](https://github.com/amplication/amplication)後端開發平台。 ----------------------------------------------------------------------- ![放大](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w7yi3kvwrniredj4lp5r.png) 我想我們都同意,如果我們要達到標準,設定後端並從頭開始是很困難的。 我知道 Appwrite 和 Supabase 在功能方面要好得多,但每種情況都是獨特的,這可能會點擊而不是那些。 ![放大](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d5wud5sef1lpwzi8zdq2.png) Amplication 旨在徹底改變可擴展且安全的 Node.js 應用程式的建立。 他們消除了重複的編碼任務,並提供可立即投入生產的基礎設施程式碼,這些程式碼根據您的規範精心定制,並遵循行業最佳實踐。 其用戶友好的介面促進了 API、資料模型、資料庫、身份驗證和授權的無縫整合。 Amplication 建立在靈活的、基於插件的架構之上,允許輕鬆定製程式碼並提供大量整合選項。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q3lc27fgvk8yearir13z.png) ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4zgix42tplg9hwko3a7u.png) 您可以閱讀[文件](https://docs.amplication.com/)並查看可用的[社群插件](https://docs.amplication.com/plugins-list/)清單。 他們還提供了[逐步教程](https://docs.amplication.com/tutorials/#step-by-step-tutorials),以幫助您使用 Angular 或 React 建立應用程式。 Amplification 在 GitHub 上擁有超過 13k 顆星,發布了 170 多個版本,因此它們不斷發展。 {% cta https://github.com/amplication/amplication %} 星狀放大 ⭐️ {% endcta %} --- 20. [Embla 旋轉木馬](https://github.com/davidjerleke/embla-carousel)-。 ------------------------------------------------------------------ ![Embla 旋轉木馬](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aj2expoo15t6xhgcm3hi.png) 我們都在應用程式中使用輪播,有時會切換到網格佈局,因為輪播並不總是好看,但這會改變您對輪播的看法。 我之所以了解 Embla Carousel,是因為 Shadcn/ui 在他們的 UI 系統中使用了它。 Embla Carousel 是一個簡單的輪播庫,具有出色的流暢運動和出色的滑動精度。它與庫無關、無依賴性且 100% 開源。 如果您不確定,我建議您查看[基本的實例](https://www.embla-carousel.com/examples/predefined/)。 ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/paqu3ozlvhk5km5746pe.png) ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8qxfvmn83et836zon4ua.png) ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abukp6j29gsaade7eci8.png) ![例子](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/locv2kqksvpl0ha8a9te.png) 我最喜歡的是視差,它可以提供非常酷且平滑的過渡。 它們支援 CDN、react、Vue、Svelte 和 Solid。 開始使用以下 npm 指令 (react)。 ``` npm install embla-carousel-react --save ``` 您可以這樣使用它。 Embla Carousel 提供了方便的 useEmblaCarousel 鉤子,用於與 React 無縫整合。最小的設定需要一個溢出包裝器和一個滾動容器。 `useEmblaCarousel`掛鉤將 Embla Carousel 選項作為第一個參數。您還需要使用 useEffect 存取 API ``` import React, { useEffect } from 'react' import useEmblaCarousel from 'embla-carousel-react' export function EmblaCarousel() { const [emblaRef, emblaApi] = useEmblaCarousel({ loop: false }) useEffect(() => { if (emblaApi) { console.log(emblaApi.slideNodes()) // Access API } }, [emblaApi]) return ( <div className="embla" ref={emblaRef}> <div className="embla__container"> <div className="embla__slide">Slide 1</div> <div className="embla__slide">Slide 2</div> <div className="embla__slide">Slide 3</div> </div> </div> ) } ``` 他們還提供了一組插件,您可以加入它們以實現自動播放等額外功能。 ``` npm install embla-carousel-autoplay --save ``` ``` import React, { useEffect } from 'react' import useEmblaCarousel from 'embla-carousel-react' import Autoplay from 'embla-carousel-autoplay' export function EmblaCarousel() { const [emblaRef] = useEmblaCarousel({ loop: false }, [Autoplay()]) return ( <div className="embla" ref={emblaRef}> <div className="embla__container"> <div className="embla__slide">Slide 1</div> <div className="embla__slide">Slide 2</div> <div className="embla__slide">Slide 3</div> </div> </div> ) } ``` 尋找[插件的完整列表](https://www.embla-carousel.com/plugins/),包括自動滾動和滾輪手勢。 您可以閱讀有關如何實現不同部分(例如斷點或上一個/下一個按鈕)的[文件](https://www.embla-carousel.com/get-started/)和[指南](https://www.embla-carousel.com/guides/)。 最讓我驚訝的部分是,您可以使用他們的[生成器](https://www.embla-carousel.com/examples/generator/)使用您自己的一組選項來產生自訂輪播。 ![發電機](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5wlq7l44bwl681644xf3.png) ![發電機](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2r1y3kr926h87clbqosw.png) 它們在 GitHub 上擁有 4.9K 顆星,並被超過 26000 名開發人員使用。如果我必須使用一個,我肯定會使用這個。 {% cta repo %} 明星名稱 ⭐️ {% endcta %} --- [21.Documenso](https://github.com/documenso/documenso) - 開源 DocuSign 替代方案。 -------------------------------------------------------------------------- ![文獻](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cttvudzx02wqsu04qt8v.gif) 如果您從事自由職業並需要簽署協議,這是最佳選擇。我們不應該浪費時間,而應該專注於重要的事情。 以數位方式簽署文件應該既快速又簡單,並且應該成為全球簽署的每個文件的最佳實踐。 如今,這在技術上相當簡單,但它也為每個簽名引入了一個新方:簽名工具提供者。 此專案的技術堆疊包括 TypeScript、Next.js、Prisma、Tailwind CSS、shadcn/ui、NextAuth.js、react-email、tRPC、@documenso/pdf-sign、React-PDF、PDF-Lib、Stripe 和韋爾塞爾。 ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ziz58jqi2qtl6p6sx62w.png) ![特徵](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f8zrln5zlywkb6k10n09.png) 免費套餐可讓您每月簽署 10 份文件,這已經足夠了。 您可以閱讀本文以了解如何[設定專案](https://github.com/documenso/documenso?tab=readme-ov-file#developer-setup)。 您可以閱讀[文件](https://github.com/documenso/documenso?tab=readme-ov-file#developer-quickstart)。 我知道這不是一個非常廣泛的用例,但您仍然可以從程式碼中學習,因此這始終是一個優點。 他們在 GitHub 上擁有超過 5800 顆星,並且發布了`v1.5`版本。 不是很流行但非常有用。 {% cta https://github.com/documenso/documenso %} 明星 documenso ⭐️ {% endcta %} --- 哇! 這花了我很長很長的時間來寫。我希望你喜歡它。 我知道人工智慧工具有時太多了,但我們應該使用它們來讓我們的工作更輕鬆。我的意思是,這就是我們所做的正確的事情,讓生活變得更輕鬆。 我嘗試涵蓋廣泛的工具。 不管怎樣,請讓我們知道您的想法以及您計劃在您的工作流程中使用這些工具嗎? 祝你有美好的一天!直到下一次。 我建立了很多技術內容,因此如果您能在 Twitter 上關注我來支持我,我將不勝感激。 |如果你喜歡這類東西, 請關注我以了解更多:) | [![用戶名 Anmol_Codes 的 Twitter 個人資料](https://img.shields.io/badge/Twitter-d5d5d5?style=for-the-badge&logo=x&logoColor=0A0209)](https://twitter.com/Anmol_Codes) [![用戶名 Anmol-Baranwal 的 GitHub 個人資料](https://img.shields.io/badge/github-181717?style=for-the-badge&logo=github&logoColor=white)](https://github.com/Anmol-Baranwal) [![用戶名 Anmol-Baranwal 的 LinkedIn 個人資料](https://img.shields.io/badge/LinkedIn-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/Anmol-Baranwal/) | |------------|----------| 關注 Taipy 以了解更多此類內容。 {% 嵌入 https://dev.to/taipy %} --- 原文出處:https://dev.to/taipy/21-tools-to-take-your-dev-skills-to-the-moon-53mf

使用 Wing 建立 React 應用程式

ReactJS 庫已經上市很久了,我們都非常了解它的強大功能。我們都知道如何使用 ReactJS 建立 UI、建立元件等等。如果您不了解 React,您可以使用大量線上免費資源。 在本部落格中,我們將研究 Wing 以及如何建立連接到 Wing 後端的 React 應用程式。 Wing 是世界上第一個在雲端服務上執行的雲端程式語言。 Wing 讓開發人員可以輕鬆建置和部署雲端應用程式。 Wing 使得在單一模型中編寫基礎設施程式碼 (terraform) 和應用程式程式碼成為可能。 Wing 附帶一個標準函式庫“cloud”,並有“Api”方法。 Api 方法表示客戶端可以透過 Internet 呼叫的 HTTP 端點的集合。此 Api 方法可用於建立一個 API,該 API 可以作為後端 API 來儲存和擷取資料。 您可以嘗試使用 Winglang 語言並了解它在[遊樂場功能](http://winglang.io/play)中的工作原理。 讓我們建立一個 React 應用程式,它將連接到使用 Wing 建立的 API。 安裝 -- 在您的裝置中安裝[Wing 工具鏈](https://www.winglang.io/)。確保您的裝置中有 Node.js 18.13.0 或更高版本。要安裝 Wing Toolchain,請在您的裝置中執行以下命令 - ``` npm install -g winglang ``` 安裝[VS Code 市場](https://marketplace.visualstudio.com/items?itemName=Monada.vscode-wing)上提供的 Wing VS code 擴充。 您可以檢查已安裝的 Wing CLI 的版本: ``` wing --version ``` 建立專案 ---- 在檔案系統中建立專案目錄並為其指定所需的名稱。在 VS Code 中開啟此目錄。在專案目錄中建立一個名為 backend 的目錄。 在後端目錄中建立一個名為“main.w”的文件,並將以下程式碼貼到其中: ``` bring cloud; let queue = new cloud.Queue(); let bucket = new cloud.Bucket(); let counter = new cloud.Counter(); queue.setConsumer(inflight (body: str): void => { let next = counter.inc(); let key = "key-{next}"; bucket.put(key, body); }); ``` *注意:如果您在整個過程中遇到任何困難,我們建議您加入我們的[Slack 頻道](https://t.winglang.io/slack)* 在本地執行 Wing 工具鏈以檢查其是否按預期工作。在終端機中執行此命令: ``` wing run backend/main.w ``` 輸出顯示將是: ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qd30iznhw0qt8io0quad.jpg) 這是 Wing Console,它充當模擬器,您可以在其中嘗試、測試和試驗雲端應用程式,看看它是否正常工作。 建立反應應用程式 -------- 現在讓我們建立一個 React App 作為前端,然後將其連接到我們建立的 Wing 後端。 我們將使用`create-react-app`在您的專案目錄中建立 React App。確保您位於主專案目錄內,而不是後端目錄內。 打開一個新終端機並執行以下命令: ``` npx create-react-app client cd client npm i --save @babel/plugin-proposal-private-property-in-object npm start ``` 一旦您看到 React 應用程式成功執行,您可以使用`CTRL+C`關閉伺服器。 連接Wing後端 -------- 現在,我們將 Wing 後端連接到我們的 React 應用程式。它將允許我們從 Wing 後端獲取資料並將其顯示在使用者介面上。 開啟`backend/main.w`檔案並將其內容替換為: 對於 Windows: ``` bring ex; bring cloud; let react = new ex.ReactApp( useBuildCommand: true, projectPath: "../client", buildCommand: "npm run start", ); ``` 對於Linux: ``` bring ex; bring cloud; let react = new ex.ReactApp( projectPath: "../client", ); ``` 使用`CTRL+C`終止`wing run`正在執行的終端,並使用設定`BROWSER=none`環境變數再次執行它: 對於 Windows: ``` set BROWSER=none wing run backend/main.w ``` 對於 Linux/Mac: ``` BROWSER=none wing run backend/main.w ``` `BROWSER=none`將限制 React 在每次執行時開啟一個新的瀏覽器視窗。 現在,您已經成功執行了一個連接到 Wing 工具鏈後端的 React 應用程式。 將配置從後端傳遞到前端 ----------- Wing 在`client/public/wing.js`中產生一個`wing.js`文件,該文件將配置從 Wing 後端傳遞到前端程式碼。 該文件的目前內容將包含: ``` // This file is generated by Wing window.wingEnv = {}; ``` 將以下程式碼加入`backend/main.w` : ``` react.addEnvironment("key1", "value1"); ``` 正在執行的`wing run`會將此鍵值對新增至`client/public/wing.js` : ``` // This file is generated by wing window.wingEnv = { "key1": "value1" }; ``` 現在,您需要將前端程式碼連結到`wing.js`檔案。將以下程式碼複製並貼上到`client/public/index.html`檔案中的`<title>`標記上方: ``` <script src="./wing.js"></script> ``` 我們將從後端獲取標題並將其顯示在 React 應用程式中。將`client/src/App.js`檔案中的「Learn React」(出現在第 18 行左右)字串替換為以下程式碼: ``` {window.wingEnv.title || "Learn React"} ``` 此表達式顯示從 React 應用程式中的 wingEnv 物件動態取得的標題。如果 wingEnv 物件沒有 title 屬性或 window.wingEnv.title 的值為假,它將顯示預設標題「Learn React」。 返回`backend/main.w`並加入以下程式碼: ``` react.addEnvironment("title", "Learn React with Wing"); ``` 這將在`wing.js`檔案中加入包含`Learn React with Wing`訊息的`title`鍵。 從後台取得標題 ------- 現在我們知道如何從客戶端向後端傳遞參數(資料)。我們可以使用這種做法在客戶端設定`window.wingEnv.apiUrl`並從後端取得標題。 我們需要透過在`backend/main.w`檔案中加入以下程式碼來啟用跨域資源共享(CORS): ``` let api = new cloud.Api( cors: true ); ``` 這會將`apiUrl`鍵和後端 API 的目前 URL 新增到`main.w`檔案中。 在後端 API 中建立`/title`路由。將此程式碼加入`backend/main.w`檔案: ``` api.get("/title", inflight () => { return { status: 200, body: "Hello from the API" }; }); ``` 當向`/tite`端點發出 GET 請求時,伺服器將使用 HTTP 狀態碼 200 和`Hello from the API`進行回應。 您可以根據您的意願更改此正文資訊。 將以下程式碼替換為`client/src/App.js`中的內容: ``` import logo from './logo.svg'; import { useEffect, useState } from "react"; import './App.css'; function App() { const [title, setTitle] = useState("Default Value"); const getTitle = async () => { const response = await fetch(`${window.wingEnv.apiUrl}/title`); setTitle(await response.text()); } useEffect(() => { getTitle(); }, []); return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> {title} </header> </div> ); } export default App; ``` 在這裡,我們使用`fetch`方法從後端 API 取得標題, `useState`和`useEffect`鉤子用於將取得的標題儲存在`title`變數中。 最終輸出將是: ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gkc56eurzhzr3n3s28f4.png) 恭喜!您已成功建立一個從 Wing 工具鏈後端取得資料的 React 應用程式。 這就是您如何將資料儲存在 Winglang 後端並獲取它以將其顯示在前端 UI 上。 有什麼地方卡住了嗎?請查看我們的影片教程,我們已經實際解釋了整個過程: {% 嵌入 https://www.youtube.com/embed/LMDnTCRXzJU?si=vuFGkqoK2fKBXb00 %} --- 原文出處:https://dev.to/ayush2390/create-react-app-with-wing-30hm

使用 AI-copilot(Next.js、gpt4、LangChain 和 CopilotKit)建立電子表格應用程式

**長話短說** -------- 在本文中,您將學習如何建立人工智慧驅動的電子表格應用程式,該應用程式允許您使用簡單的英語命令執行各種會計功能並輕鬆與資料互動。 我們將介紹如何: - 使用 Next.js 建立 Web 應用程式, - 使用 React Spreadsheet 建立電子表格應用程式,以及 - 使用 CopilotKit 將 AI 整合到軟體應用程式中。 - 讓電子表格更容易使用、更有趣 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ruxylrd07dga5ngw98np.gif) --- CopilotKit:建構應用內人工智慧副駕駛的框架 ========================== CopilotKit是一個[開源的AI副駕駛平台](https://github.com/CopilotKit/CopilotKit)。我們可以輕鬆地將強大的人工智慧整合到您的 React 應用程式中。 建造: - ChatBot:上下文感知的應用內聊天機器人,可以在應用程式內執行操作 💬 - CopilotTextArea:人工智慧驅動的文字字段,具有上下文感知自動完成和插入功能📝 - 聯合代理:應用程式內人工智慧代理,可以與您的應用程式和使用者互動🤖 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x3us3vc140aun0dvrdof.gif) {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} (請原諒 AI 的拼字錯誤並給 CopilotKit 加上星號:) 現在回到文章! --- 先決條件 ---- 要完全理解本教程,您需要對 React 或 Next.js 有基本的了解。 以下是建立人工智慧驅動的電子表格應用程式所需的工具: - [React Spreadsheet](https://github.com/iddan/react-spreadsheet) - 一個簡單的包,使我們能夠在 React 應用程式中加入電子表格。 - [OpenAI API](https://platform.openai.com/api-keys) - 提供 API 金鑰,使我們能夠使用 ChatGPT 模型執行各種任務。 - [Tavily AI](https://tavily.com/) - 一個搜尋引擎,使人工智慧代理能夠在應用程式中進行研究並存取即時知識。 - [CopilotKit](https://github.com/CopilotKit) - 一個開源副駕駛框架,用於建立自訂 AI 聊天機器人、應用程式內 AI 代理程式和文字區域。 專案設定和套件安裝 --------- 首先,透過在終端機中執行以下程式碼片段來建立 Next.js 應用程式: ``` npx create-next-app spreadsheet-app ``` 選擇您首選的配置設定。在本教學中,我們將使用 TypeScript 和 Next.js App Router。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f2zg8z22tdgmlv4wmfil.png) 接下來,安裝[OpenAI 函式庫](https://platform.openai.com/docs/introduction)、 [Heroicons](https://www.npmjs.com/package/@heroicons/react)和[React Spreadsheet](https://github.com/iddan/react-spreadsheet)套件及其相依性: ``` npm install openai react-spreadsheet scheduler @heroicons/react ``` 最後,安裝 CopilotKit 軟體套件。這些套件使我們能夠從 React 狀態檢索資料並將 AI copilot 新增至應用程式。 ``` npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend ``` 恭喜!您現在已準備好建立應用程式。 --- 建立電子表格應用程式 ---------- 在本節中,我將引導您使用 React Spreadsheet 建立電子表格應用程式。 該應用程式分為兩個元件: `Sidebar`和`SingleSpreadsheet` 。 要設定這些元件,請導航至 Next.js 應用程式資料夾並建立一個包含以下檔案的`components`資料夾: ``` cd app mkdir components && cd components touch Sidebar.tsx SingleSpreadsheet.tsx ``` ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bd9crph3qdenb2eikfoh.png) 將新建立的元件匯入到**`app/page.tsx`**檔案中。 ``` "use client"; import React, { useState } from "react"; //👇🏻 import the components import { SpreadsheetData } from "./types"; import Sidebar from "./components/Sidebar"; import SingleSpreadsheet from "./components/SingleSpreadsheet"; const Main = () => { return ( <div className='flex'> <p>Hello world</p> </div> ); }; export default Main; ``` 接下來,建立將包含電子表格資料的 React 狀態,並將它們作為 props 傳遞到元件中。 ``` const Main = () => { //👇🏻 holds the title and data within a spreadsheet const [spreadsheets, setSpreadsheets] = React.useState<SpreadsheetData[]>([ { title: "Spreadsheet 1", data: [ [{ value: "" }, { value: "" }, { value: "" }], [{ value: "" }, { value: "" }, { value: "" }], [{ value: "" }, { value: "" }, { value: "" }], ], }, ]); //👇🏻 represents the index of a spreadsheet const [selectedSpreadsheetIndex, setSelectedSpreadsheetIndex] = useState(0); return ( <div className='flex'> <Sidebar spreadsheets={spreadsheets} selectedSpreadsheetIndex={selectedSpreadsheetIndex} setSelectedSpreadsheetIndex={setSelectedSpreadsheetIndex} /> <SingleSpreadsheet spreadsheet={spreadsheets[selectedSpreadsheetIndex]} setSpreadsheet={(spreadsheet) => { setSpreadsheets((prev) => { console.log("setSpreadsheet", spreadsheet); const newSpreadsheets = [...prev]; newSpreadsheets[selectedSpreadsheetIndex] = spreadsheet; return newSpreadsheets; }); }} /> </div> ); }; ``` 此程式碼片段建立了 React 狀態,用於保存電子表格資料及其索引,並將它們作為 props 傳遞到元件中。 `Sidebar`元件接受所有可用的電子表格, `SingleSpreadsheet`元件接收所有電子表格,包括更新電子表格資料的`setSpreadsheet`函數。 將下面的程式碼片段複製到`Sidebar.tsx`檔案中。它顯示應用程式中的所有電子表格,並允許使用者在它們之間進行切換。 ``` import React from "react"; import { SpreadsheetData } from "../types"; interface SidebarProps { spreadsheets: SpreadsheetData[]; selectedSpreadsheetIndex: number; setSelectedSpreadsheetIndex: (index: number) => void; } const Sidebar = ({ spreadsheets, selectedSpreadsheetIndex, setSelectedSpreadsheetIndex, }: SidebarProps) => { return ( <div className='w-64 h-screen bg-gray-800 text-white overflow-auto p-5'> <ul> {spreadsheets.map((spreadsheet, index) => ( <li key={index} className={`mb-4 cursor-pointer ${ index === selectedSpreadsheetIndex ? "ring-2 ring-blue-500 ring-inset p-3 rounded-lg" : "p-3" }`} onClick={() => setSelectedSpreadsheetIndex(index)} > {spreadsheet.title} </li> ))} </ul> </div> ); }; export default Sidebar; ``` ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c36qccuwa0knqokag5mk.gif) 更新`SingleSpreadsheet.tsx`文件,如下所示: ``` import React from "react"; import Spreadsheet from "react-spreadsheet"; import { SpreadsheetData, SpreadsheetRow } from "../types"; interface MainAreaProps { spreadsheet: SpreadsheetData; setSpreadsheet: (spreadsheet: SpreadsheetData) => void; } //👇🏻 adds a new row to the spreadsheet const addRow = () => { const numberOfColumns = spreadsheet.rows[0].length; const newRow: SpreadsheetRow = []; for (let i = 0; i < numberOfColumns; i++) { newRow.push({ value: "" }); } setSpreadsheet({ ...spreadsheet, rows: [...spreadsheet.rows, newRow], }); }; //👇🏻 adds a new column to the spreadsheet const addColumn = () => { const spreadsheetData = [...spreadsheet.data]; for (let i = 0; i < spreadsheet.data.length; i++) { spreadsheet.data[i].push({ value: "" }); } setSpreadsheet({ ...spreadsheet, data: spreadsheetData, }); }; const SingleSpreadsheet = ({ spreadsheet, setSpreadsheet }: MainAreaProps) => { return ( <div className='flex-1 overflow-auto p-5'> {/** -- Spreadsheet title ---*/} <div className='flex items-start'> {/** -- Spreadsheet rows and columns---*/} {/** -- Add column button ---*/} </div> {/** -- Add row button ---*/} </div> ); }; export default SingleSpreadsheet; ``` - 從上面的程式碼片段來看, ``` - The `SingleSpreadsheet.tsx` file includes the addRow and addColumn functions. ``` ``` - The `addRow` function calculates the current number of rows, adds a new row, and updates the spreadsheet accordingly. ``` ``` - Similarly, the `addColumn` function adds a new column to the spreadsheet. ``` ``` - The `SingleSpreadsheet` component renders placeholders for the user interface elements. ``` 更新`SingleSpreadsheet`元件以呈現電子表格標題、其資料以及新增行和列按鈕。 ``` return ( <div className='flex-1 overflow-auto p-5'> {/** -- Spreadsheet title ---*/} <input type='text' value={spreadsheet.title} className='w-full p-2 mb-5 text-center text-2xl font-bold outline-none bg-transparent' onChange={(e) => setSpreadsheet({ ...spreadsheet, title: e.target.value }) } /> {/** -- Spreadsheet rows and columns---*/} <div className='flex items-start'> <Spreadsheet data={spreadsheet.data} onChange={(data) => { console.log("data", data); setSpreadsheet({ ...spreadsheet, data: data as any }); }} /> {/** -- Add column button ---*/} <button className='bg-blue-500 text-white rounded-lg ml-6 w-8 h-8 mt-0.5' onClick={addColumn} > + </button> </div> {/** -- Add row button ---*/} <button className='bg-blue-500 text-white rounded-lg w-8 h-8 mt-5 ' onClick={addRow} > + </button> </div> ); ``` 為了確保一切按預期工作,請在`app`資料夾中建立一個`types.ts`文件,其中包含應用程式中聲明的所有靜態類型。 ``` export interface Cell { value: string; } export type SpreadsheetRow = Cell[]; export interface SpreadsheetData { title: string; rows: SpreadsheetRow[]; } ``` 恭喜! 🎉 您的電子表格應用程式應該可以完美執行。在接下來的部分中,您將了解如何新增 AI 副駕駛,以使用 CopilotKit 自動執行各種任務。 --- 使用 CopilotKit 改進應用程式功能 ---------------------- 在這裡,您將學習如何將 AI 副駕駛加入到電子表格應用程式,以使用 CopilotKit 自動執行複雜的操作。 CopilotKit 提供前端和[後端](https://docs.copilotkit.ai/getting-started/quickstart-backend)套件。它們使您能夠插入 React 狀態並使用 AI 代理在後端處理應用程式資料。 首先,我們將 CopilotKit React 元件新增到應用程式前端。 ### 將 CopilotKit 加入前端 在`app/page.tsx`中,將以下程式碼片段加入`Main`元件的頂部。 ``` import "@copilotkit/react-ui/styles.css"; import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import { INSTRUCTIONS } from "./instructions"; const HomePage = () => { return ( <CopilotKit url='/api/copilotkit'> <CopilotSidebar instructions={INSTRUCTIONS} labels={{ initial: "Welcome to the spreadsheet app! How can I help you?", }} defaultOpen={true} clickOutsideToClose={false} > <Main /> </CopilotSidebar> </CopilotKit> ); }; const Main = () => { //--- Main component // }; export default HomePage; ``` - 從上面的程式碼片段來看, ``` - I imported the CopilotKit, its sidebar component, and CSS file to use its frontend components within the application. ``` ``` - The [CopilotKit component](https://docs.copilotkit.ai/reference/CopilotKit) accepts a `url` prop that represents the API server route where CopilotKit will be configured. ``` ``` - The Copilot component also renders the [CopilotSidebar component](https://docs.copilotkit.ai/reference/CopilotSidebar) , allowing users to provide custom instructions to the AI copilot within the application. ``` ``` - Lastly, you can export the `HomePage` component containing the `CopilotSidebar` and the `Main` components. ``` 從上面的程式碼片段中,您會注意到`CopilotSidebar`元件有一個`instructions`屬性。此屬性使您能夠為 CopilotKit 提供額外的上下文或指導。 因此,在`app`資料夾中建立`instructions.ts`檔案並將這些[命令](https://github.com/CopilotKit/spreadsheet-demo/blob/main/src/app/instructions.ts)複製到該檔案中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/whs8k2ly9as7j4wn6h5o.png) 接下來,您需要將 CopilotKit 插入應用程式的狀態以存取應用程式的資料。為了實現這一點,CopilotKit 提供了兩個鉤子: [useCopilotAction](https://docs.copilotkit.ai/reference/useCopilotAction)和[useMakeCopilotReadable](https://docs.copilotkit.ai/reference/useMakeCopilotReadable) 。 [useCopilotAction](https://docs.copilotkit.ai/reference/useCopilotAction)掛鉤可讓您定義 CopilotKit 執行的動作。它接受包含以下參數的物件: - `name` - 操作的名稱。 - `description` - 操作的描述。 - `parameters` - 包含所需參數清單的陣列。 - `render` - 預設的自訂函數或字串。 - `handler` - 由操作觸發的可執行函數。 ``` useCopilotAction({ name: "sayHello", description: "Say hello to someone.", parameters: [ { name: "name", type: "string", description: "name of the person to say greet", }, ], render: "Process greeting message...", handler: async ({ name }) => { alert(`Hello, ${name}!`); }, }); ``` [useMakeCopilotReadable](https://docs.copilotkit.ai/reference/useMakeCopilotReadable)掛鉤向 CopilotKit 提供應用程式狀態。 ``` import { useMakeCopilotReadable } from "@copilotkit/react-core"; const appState = ...; useMakeCopilotReadable(JSON.stringify(appState)); ``` 現在,讓我們回到電子表格應用程式。在`SingleSpreadsheet`元件中,將應用程式狀態傳遞到 CopilotKit 中,如下所示。 ``` import { useCopilotAction, useMakeCopilotReadable, } from "@copilotkit/react-core"; const SingleSpreadsheet = ({ spreadsheet, setSpreadsheet }: MainAreaProps) => { //👇🏻 hook for providing the application state useMakeCopilotReadable( "This is the current spreadsheet: " + JSON.stringify(spreadsheet) ); // --- other lines of code }; ``` 接下來,您需要在`SingleSpreadsheet`元件中新增兩個操作,該元件在使用者更新電子表格資料並使用 CopilotKit 新增資料行時執行。 在繼續之前,請在`app`資料夾中建立一個包含`canonicalSpreadsheetData.ts`檔案的`utils`資料夾。 ``` cd app mkdir utils && cd utils touch canonicalSpreadsheetData.ts ``` 將下面的程式碼片段複製到檔案中。它接受對電子表格所做的更新,並將其轉換為電子表格中資料行所需的格式。 ``` import { SpreadsheetRow } from "../types" export interface RowLike { cells: CellLike[] | undefined; } export interface CellLike { value: string; } export function canonicalSpreadsheetData( rows: RowLike[] | undefined ): SpreadsheetRow[] { const canonicalRows: SpreadsheetRow[] = []; for (const row of rows || []) { const canonicalRow: SpreadsheetRow = []; for (const cell of row.cells || []) { canonicalRow.push({value: cell.value}); } canonicalRows.push(canonicalRow); } return canonicalRows; } ``` 現在,讓我們使用`SingleSpreadsheet`元件中的`useCopilotAction`掛鉤建立操作。複製下面的第一個操作: ``` import { canonicalSpreadsheetData } from "../utils/canonicalSpreadsheetData"; import { PreviewSpreadsheetChanges } from "./PreviewSpreadsheetChanges"; import { SpreadsheetData, SpreadsheetRow } from "../types"; import { useCopilotAction } from "@copilotkit/react-core"; useCopilotAction({ name: "suggestSpreadsheetOverride", description: "Suggest an override of the current spreadsheet", parameters: [ { name: "rows", type: "object[]", description: "The rows of the spreadsheet", attributes: [ { name: "cells", type: "object[]", description: "The cells of the row", attributes: [ { name: "value", type: "string", description: "The value of the cell", }, ], }, ], }, { name: "title", type: "string", description: "The title of the spreadsheet", required: false, }, ], render: (props) => { const { rows } = props.args const newRows = canonicalSpreadsheetData(rows); return ( <PreviewSpreadsheetChanges preCommitTitle="Replace contents" postCommitTitle="Changes committed" newRows={newRows} commit={(rows) => { const updatedSpreadsheet: SpreadsheetData = { title: spreadsheet.title, rows: rows, }; setSpreadsheet(updatedSpreadsheet); }} /> ) }, handler: ({ rows, title }) => { // Do nothing. // The preview component will optionally handle committing the changes. }, }); ``` 上面的程式碼片段執行使用者的任務並使用 CopilotKit 產生 UI 功能顯示結果預覽。 `suggestSpreadsheetOverride`操作傳回一個自訂元件 ( `PreviewSpreadsheetChanges` ),該元件接受以下內容為 props: - 要新增到電子表格的新資料行, - 一些文字 - `preCommitTitle`和`postCommitTitle` ,以及 - 更新電子表格的`commit`函數。 您很快就會學會如何使用它們。 在元件資料夾中建立`PreviewSpreadsheetChanges`元件,並將下列程式碼片段複製到檔案中: ``` import { CheckCircleIcon } from '@heroicons/react/20/solid' import { SpreadsheetRow } from '../types'; import { useState } from 'react'; import Spreadsheet from 'react-spreadsheet'; export interface PreviewSpreadsheetChanges { preCommitTitle: string; postCommitTitle: string; newRows: SpreadsheetRow[]; commit: (rows: SpreadsheetRow[]) => void; } export function PreviewSpreadsheetChanges(props: PreviewSpreadsheetChanges) { const [changesCommitted, setChangesCommitted] = useState(false); const commitChangesButton = () => { return ( <button className="inline-flex items-center gap-x-2 rounded-md bg-indigo-600 px-3.5 py-2.5 text-sm font-semibold text-white shadow-sm hover:bg-indigo-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-indigo-600" onClick={() => { props.commit(props.newRows); setChangesCommitted(true); }} > {props.preCommitTitle} </button> ); } const changesCommittedButtonPlaceholder = () => { return ( <button className=" inline-flex items-center gap-x-2 rounded-md bg-gray-100 px-3.5 py-2.5 text-sm font-semibold text-green-600 shadow-sm cursor-not-allowed" disabled > {props.postCommitTitle} <CheckCircleIcon className="-mr-0.5 h-5 w-5" aria-hidden="true" /> </button> ); } return ( <div className="flex flex-col"> <Spreadsheet data={props.newRows} /> <div className="mt-5"> {changesCommitted ? changesCommittedButtonPlaceholder() : commitChangesButton() } </div> </div> ); } ``` `PreviewSpreadsheetChanges`元件傳回一個電子表格,其中包含從請求產生的資料和一個按鈕(帶有`preCommitTitle`文字),該按鈕允許您將這些變更提交到主電子表格表(透過觸發`commit`函數)。這可確保您在將結果新增至電子表格之前對結果感到滿意。 將下面的第二個操作加入到`SingleSpreadsheet`元件。 ``` useCopilotAction({ name: "appendToSpreadsheet", description: "Append rows to the current spreadsheet", parameters: [ { name: "rows", type: "object[]", description: "The new rows of the spreadsheet", attributes: [ { name: "cells", type: "object[]", description: "The cells of the row", attributes: [ { name: "value", type: "string", description: "The value of the cell", }, ], }, ], }, ], render: (props) => { const status = props.status; const { rows } = props.args const newRows = canonicalSpreadsheetData(rows); return ( <div> <p>Status: {status}</p> <Spreadsheet data={newRows} /> </div> ) }, handler: ({ rows }) => { const canonicalRows = canonicalSpreadsheetData(rows); const updatedSpreadsheet: SpreadsheetData = { title: spreadsheet.title, rows: [...spreadsheet.rows, ...canonicalRows], }; setSpreadsheet(updatedSpreadsheet); }, }); ``` `appendToSpreadsheet`操作透過在電子表格中新增資料行來更新電子表格。 以下是操作的簡短示範: \[https://www.youtube.com/watch?v=kGQ9xl5mSoQ\] 最後,在`Main`元件中新增一個操作,以便在使用者提供指令時建立一個新的電子表格。 ``` useCopilotAction({ name: "createSpreadsheet", description: "Create a new spreadsheet", parameters: [ { name: "rows", type: "object[]", description: "The rows of the spreadsheet", attributes: [ { name: "cells", type: "object[]", description: "The cells of the row", attributes: [ { name: "value", type: "string", description: "The value of the cell", }, ], }, ], }, { name: "title", type: "string", description: "The title of the spreadsheet", }, ], render: (props) => { const { rows, title } = props.args; const newRows = canonicalSpreadsheetData(rows); return ( <PreviewSpreadsheetChanges preCommitTitle="Create spreadsheet" postCommitTitle="Spreadsheet created" newRows={newRows} commit={ (rows) => { const newSpreadsheet: SpreadsheetData = { title: title || "Untitled Spreadsheet", rows: rows, }; setSpreadsheets((prev) => [...prev, newSpreadsheet]); setSelectedSpreadsheetIndex(spreadsheets.length); }} /> ); }, handler: ({ rows, title }) => { // Do nothing. // The preview component will optionally handle committing the changes. }, }); ``` 恭喜!您已成功為此應用程式建立所需的操作。現在,讓我們將應用程式連接到 Copilotkit 後端。 ### 將 Tavily AI 和 OpenAI 加入到 CopilotKit 在本教程的開頭,我向您介紹了[Tavily AI](https://tavily.com/) (一個為 AI 代理提供知識的搜尋引擎)和 OpenAI(一個使我們能夠存取[GPT-4 AI 模型的](https://openai.com/gpt-4)庫)。 在本部分中,您將了解如何取得 Tavily 和 OpenAI API 金鑰並將它們整合到 CopilotKit 中以建立高級智慧應用程式。 造訪[Tavily AI 網站](https://app.tavily.com/sign-in),建立一個帳戶,然後將您的 API 金鑰複製到您專案的`.env.local`檔案中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w8shpxr5hh9r9kggk1jv.png) 接下來,導覽至[OpenAI 開發者平台](https://platform.openai.com/api-keys),建立 API 金鑰,並將其複製到`.env.local`檔案中。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f4ugtobr70wg6z6ru3cj.png) 以下是`.env.local`檔案的預覽,其中包括 API 金鑰並指定要使用的 OpenAI 模型。請注意,存取 GPT-4 模型需要[訂閱 ChatGPT Plus](https://openai.com/chatgpt/pricing) 。 ``` TAVILY_API_KEY=<your_API_key> OPENAI_MODEL=gpt-4-1106-preview OPENAI_API_KEY=<your_API_key> ``` 回到我們的應用程式,您需要為 Copilot 建立 API 路由。因此,建立一個包含`route.ts`的`api/copilotkit`資料夾並新增一個`tavily.ts`檔案。 ``` cd app mkdir api && cd api mkdir copilotkit && cd copilotkit touch route.ts tavily.ts ``` 在`tavily.ts`檔案中建立一個函數,該函數接受使用者的查詢,使用 Tavily Search API 對查詢進行研究,並使用[OpenAI GPT-4 模型](https://openai.com/gpt-4)總結結果。 ``` import OpenAI from "openai"; export async function research(query: string) { //👇🏻 sends the request to the Tavily Search API const response = await fetch("https://api.tavily.com/search", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ api_key: process.env.TAVILY_API_KEY, query, search_depth: "basic", include_answer: true, include_images: false, include_raw_content: false, max_results: 20, }), }); //👇🏻 the response const responseJson = await response.json(); const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY! }); //👇🏻 passes the response into the OpenAI GPT-4 model const completion = await openai.chat.completions.create({ messages: [ { role: "system", content: `Summarize the following JSON to answer the research query \`"${query}"\`: ${JSON.stringify( responseJson )} in plain English.`, }, ], model: process.env.OPENAI_MODEL, }); //👇🏻 returns the result return completion.choices[0].message.content; } ``` 最後,您可以透過將使用者的查詢傳遞到函數中並向 CopilotKit 提供其回應來執行`route.ts`檔案中的`research`函數。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; import { Action } from "@copilotkit/shared"; import { research } from "./tavily"; //👇🏻 carries out a research on the user's query const researchAction: Action<any> = { name: "research", description: "Call this function to conduct research on a certain query.", parameters: [ { name: "query", type: "string", description: "The query for doing research. 5 characters or longer. Might be multiple words", }, ], handler: async ({ query }) => { console.log("Research query: ", query); const result = await research(query); console.log("Research result: ", result); return result; }, }; export async function POST(req: Request): Promise<Response> { const actions: Action<any>[] = []; if (process.env.TAVILY_API_KEY!) { actions.push(researchAction); } const copilotKit = new CopilotBackend({ actions: actions, }); const openaiModel = process.env.OPENAI_MODEL; return copilotKit.response(req, new OpenAIAdapter({ model: openaiModel })); } ``` 恭喜!您已完成本教學的專案。 結論 -- [CopilotKit](https://copilotkit.ai/)是一款令人難以置信的工具,可讓您在幾分鐘內將 AI Copilot 加入到您的產品中。無論您是對人工智慧聊天機器人和助理感興趣,還是對複雜任務的自動化感興趣,CopilotKit 都能讓您輕鬆實現。 如果您需要建立 AI 產品或將 AI 工具整合到您的軟體應用程式中,您應該考慮 CopilotKit。 您可以在 GitHub 上找到本教學的源程式碼: https://github.com/CopilotKit/spreadsheet-demo 感謝您的閱讀! --- 原文出處:https://dev.to/copilotkit/build-an-ai-powered-spreadsheet-app-nextjs-langchain-copilotkit-109d

給新手開發者的 Git 指南

🩺 醫生有聽診器。 🔧 機械師有扳手。 👨‍💻 我們開發人員,有 Git。 您是否注意到 Git 對於程式碼工作來說是如此不可或缺,以至於人們幾乎從未將其包含在他們的技術堆疊或簡歷中?假設你已經知道了,或至少足以應付,但你知道嗎? Git 是一個版本控制系統(VCS)。無所不在的技術使我們能夠儲存、更改程式碼並與他人合作。 > 🚨 作為免責聲明,我想指出 Git 是一個很大的話題。 Git 書籍已經出版,部落格文章也可能被誤認為是學術論文。這不是我來這裡的目的。**我不是 Git 專家**。我的目標是寫一篇我希望在學習 Git 時擁有的 Git 基礎文章。 作為開發人員,我們的日常工作圍繞著閱讀、編寫和審查程式碼。 Git 可以說是我們使用的最重要的工具之一。身為開發人員,掌握 Git 提供的特性和功能是您可以對自己進行的最佳投資之一。 讓我們開始吧 ![git](https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExMXZqODl2Zjk5cTUzYWo3Nnptam1qYWdqYm4xcmY5dXEyY2RzZWZrbCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/m0HehxSuVPd9CE3L4H/giphy.gif) > 如果您覺得我錯過了或應該更詳細地了解特定命令,請在下面的評論中告訴我。我將相應地更新這篇文章。 🙏 --- 當我們談論這個話題時 ---------- 如果您希望將 Git 技能運用到工作中並願意為 Glasskube 做出貢獻,我們於 2 月正式推出,我們的目標是成為 Kubernetes 套件管理的預設預設解決方案。有了您的支持,我們就能實現這一目標。表達您支持的最佳方式是在 GitHub 上為我們加註星標 ⭐ [![連小貓也喜歡送星星](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzaxhc3f53sggz7v3bw4.jpeg)](https://github.com/glasskube/glasskube) --- 讓我們打好基礎 ------- Git 有沒有讓你感覺像 Peter Griffin 一樣? 如果您沒有以正確的方式學習 Git,您可能會不斷地摸不著頭腦,陷入同樣的問題,或者後悔有一天在終端中出現另一個合併衝突。讓我們定義一些基本的 Git 概念來確保這種情況不會發生。 ![git-2](https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExNjBqNHlnNjgwZHl4ZmdtMW8wbGJjYWJ5MmQyN2x4YXJpeXAxNWFsZCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/jcKiy2CqRIYM8W3E4p/giphy.gif) ### 分公司 在 Git 儲存庫中,您會發現一條開發主線,通常名為「main」或「master」( [已棄用](https://github.blog/changelog/2020-10-01-the-default-branch-for-newly-created-repositories-is-now-main/)),其中有幾個[分支](https://git-scm.com/book/en/v2/Git-Branching-Branches-in-a-Nutshell)分支。這些分支代表同時的工作流程,使開發人員能夠在同一專案中同時處理多個功能或修復。 ![Git 分支](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t3p5q80hldckku20urm0.png) ### 提交 Git 提交作為更新程式碼的捆綁包,捕獲專案程式碼在特定時間點的快照。每次提交都會記錄自上次記錄以來所做的更改,共同建立專案開發旅程的全面歷史。 ![Git 提交](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dcjp286j11bqkx0k9w35.png) 當引用提交時,您通常會使用其唯一標識的加密[雜湊](https://www.mikestreety.co.uk/blog/the-git-commit-hash/)。 例子: ``` git show abc123def456789 ``` 這顯示了有關該哈希提交的詳細資訊。 ### 標籤 Git[標籤](https://git-scm.com/book/en/v2/Git-Basics-Tagging)充當 Git 歷史中的地標,通常標記專案開發中的重要里程碑,例如`releases` 、 `versions`或`standout commits` 。這些標籤對於標記特定時間點非常有價值,通常代表專案旅程中的起點或主要成就。 ![Git 標籤](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06uilykiq1ky6dtnr3ez.png) ### 頭 目前簽出分支上的最新提交由`HEAD`指示,充當儲存庫中任何引用的指標。當您位於特定分支時, `HEAD`指向該分支上的最新提交。有時, `HEAD`可以直接指向特定的提交( `detached HEAD`狀態),而不是指向分支的尖端。 ### 階段 了解 Git 階段對於導航 Git 工作流程至關重要。它們代表文件更改在提交到儲存庫之前發生的邏輯轉換。 讓我們深入研究一下 Git 階段的概念: ![Git 階段](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/96ndc8w183kh0tcb3uxb.png) #### 工作目錄👷 `working directory`是您編輯、修改和建立專案文件的位置。表示本機上檔案的目前狀態。 #### 暫存區🚉 `staging`區域就像一個保留區域或預提交區域,您可以在其中準備更改,然後再將更改提交到儲存庫。 > 這裡有用的指令: `git add` > `git rm`也可用於取消暫存更改 #### 本地儲存庫🗄️ 本機儲存庫是 Git 永久儲存已提交變更的位置。它允許您查看專案的歷史記錄,恢復到以前的狀態,並與同一程式碼庫上的其他人進行協作。 > 您可以使用以下指令提交暫存區域中準備好的變更: `git commit` #### 遠端儲存庫🛫 遠端儲存庫是一個集中位置,通常託管在伺服器(例如 GitHub、GitLab 或 Bitbucket)上,您可以在其中與其他人共用專案並進行協作。 > 您可以使用`git push`和`git pull`等命令將提交的變更從本機儲存庫推送/拉取到遠端儲存庫。 Git 入門 ------ 好吧,你必須從某個地方開始,在 Git 中那就是你的`workspace` 。您可以`fork`或`clone`現有儲存庫並擁有該工作區的副本,或者如果您在電腦上的新本機資料夾中全新開始,則必須使用`git init`將其轉換為 git 儲存庫。不容忽視的下一步是設定您的憑證。 ![Source: Shuai Li](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fqr8mylqjo91zurb7gmi.png) ### 憑證設定 當執行推送和拉取到遠端儲存庫時,您不想每次都輸入使用者名稱和密碼,只需執行以下命令即可避免這種情況: ``` git config --global credential.helper store ``` 第一次與遠端儲存庫互動時,Git 會提示您輸入使用者名稱和密碼。之後,您將不再收到提示 > 請務必注意,憑證以純文字格式儲存在`.git-credentials`檔案中。 若要檢查已配置的憑證,您可以使用下列命令: ``` git config --global credential.helper ``` ### 與分公司合作 在本地工作時,了解您目前所在的分支至關重要。這些命令很有幫助: ``` # Will show the changes in the local repository git branch # Or create a branch directly with git branch feature-branch-name ``` 若要在分支之間轉換,請使用: ``` git switch ``` 除了在它們之間進行轉換之外,您還可以使用: ``` git checkout # A shortcut to switch to a branch that is yet to be created with the -b flag git checkout -b feature-branch-name ``` 若要檢查儲存庫的狀態,請使用: ``` git status ``` 始終清楚了解當前分支的一個好方法是在終端機中查看它。許多終端插件可以幫助解決這個問題。這是[一個](https://gist.github.com/joseluisq/1e96c54fa4e1e5647940)。 ![終端視圖](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nycmbxgrtplax7q83g3n.png) ### 使用提交 在處理提交時,使用 git commit -m 記錄更改,使用 git amend 修改最近的提交,並盡力遵守[提交訊息約定](https://gist.github.com/qoomon/5dfcdf8eec66a051ecd85625518cfd13)。 ``` # Make sure to add a message to each commit git commit -m "meaningful message" ``` 如果您對上次提交進行了更改,則不必完全建立另一個提交,您可以使用 --amend 標誌來使用分階段變更來修改最近的提交 ``` # make your changes git add . git commit --amend # This will open your default text editor to modify the commit message if needed. git push origin your_branch --force ``` > ⚠️ 使用`--force`時要小心,因為它有可能涵蓋目標分支的歷史記錄。通常應避免在 main/master 分支上應用它。 > 根據經驗,最好經常提交,以避免遺失進度或意外重置未暫存的變更。之後可以透過壓縮多個提交或進行互動式變基來重寫歷史記錄。 使用`git log`顯示按時間順序排列的提交列表,從最近的提交開始並按時間倒推 操縱歷史 ---- 操縱歷史涉及一些強大的命令。 `Rebase`重寫提交歷史記錄, `Squashing`將多個提交合併為一個,而`Cherry-picking`選擇特定提交。 ### 變基和合併 將變基與合併進行比較是有意義的,因為它們的目標相同,但實現方式不同。關鍵的差異在於變基重寫了專案的歷史。對於重視清晰且易於理解的專案歷史的專案來說,這是理想的選擇。另一方面,合併透過產生新的合併提交來維護兩個分支歷史記錄。 在變基期間,功能分支的提交歷史記錄在移動到主分支的`HEAD`時會被重組 ![狐狸](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ytea832muxycodnkdlma.png) 這裡的工作流程非常簡單。 確保您位於要變基的分支上並從遠端儲存庫取得最新變更: ``` git checkout your_branch git fetch ``` 現在選擇您想要變基的分支並執行以下命令: ``` git rebase upstream_branch ``` 變基後,如果分支已推送到遠端儲存庫,您可能需要強制推送變更: ``` git push origin your_branch --force ``` > ⚠️ 使用`--force`時要小心,因為它有可能涵蓋目標分支的歷史記錄。通常應避免在 main/master 分支上應用它。 ### 擠壓 Git 壓縮用於將多個提交壓縮為單一、有凝聚力的提交。 ![git 擠壓](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/owzri2ufj3meqhtjjpc0.png) 這個概念很容易理解,如果使用的統一程式碼的方法是變基,則特別有用,因為歷史記錄會被改變,所以注意對專案歷史記錄的影響很重要。有時我很難執行擠壓,特別是使用互動式變基,幸運的是我們有一些工具可以幫助我們。這是我首選的壓縮方法,其中涉及將 HEAD 指標向後移動 X 次提交,同時保留分階段的變更。 ``` # Change to the number after HEAD~ depending on the commits you want to squash git reset --soft HEAD~X git commit -m "Your squashed commit message" git push origin your_branch --force ``` > ⚠️ 使用`--force`時要小心,因為它有可能涵蓋目標分支的歷史記錄。通常應避免在 main/master 分支上應用它。 ### 採櫻桃 櫻桃採摘對於選擇性地合併從一個分支到另一個分支的更改非常有用,特別是當合併整個分支不合需要或不可行時。然而,明智地使用櫻桃選擇很重要,因為如果應用不當,可能會導致重複提交和不同的歷史記錄 ![採櫻桃](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wxe90o4u26mikikee9f1.png) 要先執行此操作,您必須確定要選擇的提交的提交哈希,您可以使用`git log`來執行此操作。一旦確定了提交哈希,您就可以執行: ``` git checkout target_branch git cherry-pick <commit-hash> # Do this multiple times if multiple commits are wanted git push origin target_branch ``` 高級 Git 指令 --------- ### 簽署提交 對提交進行簽名是一種驗證 Git 中提交的真實性和完整性的方法。它允許您使用 GPG (GNU Privacy Guard) 金鑰對您的提交進行加密簽名,從而向 Git 保證您確實是該提交的作者。您可以透過建立 GPG 金鑰並將 Git 配置為在提交時使用該金鑰來實現此目的。 步驟如下: ``` # Generate a GPG key gpg --gen-key # Configure Git to Use Your GPG Key git config --global user.signingkey <your-gpg-key-id> # Add the public key to your GitHub account # Signing your commits with the -S flag git commit -S -m "Your commit message" # View signed commits git log --show-signature ``` ### 轉發日誌 我們還沒有探討的一個主題是 Git 引用,它們是指向儲存庫中各種物件的指針,主要是提交,還有標籤和分支。它們可作為 Git 歷史記錄中的命名點,允許使用者瀏覽儲存庫的時間軸並存取專案的特定快照。了解如何導航 git 引用非常有用,他們可以使用 git reflog 來做到這一點。 以下是一些好處: - 恢復遺失的提交或分支 - 除錯和故障排除 - 糾正錯誤 ### 互動式變基 互動式變基是一個強大的 Git 功能,可讓您以互動方式重寫提交歷史記錄。它使您能夠在將提交應用到分支之前對其進行修改、重新排序、組合或刪除。 為了使用它,您必須熟悉可能的操作,例如: - 選擇(“p”) - 改寫(“r”) - 編輯(“e”) - 壁球(“s”) - 刪除(“d”) ![互動式變基](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/98sngs9j2dl5awcmm8dt.png) 這是一個有用的[影片,](https://www.youtube.com/watch?v=qsTthZi23VE)用於學習如何在終端中執行互動式變基,我還在部落格文章的底部連結了一個有用的工具。 與 Git 協作 -------- ### 起源與上游 **來源**是複製本機 Git 儲存庫時與本機 Git 儲存庫關聯的預設遠端儲存庫。如果您分叉了一個儲存庫,那麼預設情況下該分叉將成為您的「原始」儲存庫。 另一方面,**上游**指的是您的儲存庫分叉的原始儲存庫。 為了讓您的分叉儲存庫與原始專案的最新更改保持同步,您可以從「上游」儲存庫中 git 取得更改,並將它們合併或變基到本機儲存庫中。 若要查看與本機 Git 儲存庫關聯的遠端儲存庫,請執行: ``` git remote -v ``` ### 衝突 不要驚慌,當嘗試合併或變基分支並檢測到衝突時,這只意味著存儲庫中同一文件或文件的不同版本之間存在衝突的更改,並且可以輕鬆解決(大多數情況下)。 ![合併衝突](https://media3.giphy.com/media/v1.Y2lkPTc5MGI3NjExbXRiM3o5cWd0OGZ3Z2NudGhlb2gyaXhheTRmcGx0bW5sN3UzNXJhYSZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/cFkiFMDg3iFoI/giphy.gif) 它們通常在受影響的文件中指示,Git 在其中插入衝突標記`<<<<<<<` 、 `=======`和`>>>>>>>`以突出顯示衝突部分。 決定保留、修改或刪除哪些更改,確保產生的程式碼有意義並保留預期的功能。 手動解決衝突檔案中的衝突後,刪除衝突標記`<<<<<<<` 、 `=======`和`>>>>>>>`並根據需要調整程式碼。 對解決方案感到滿意後,請儲存衝突文件中的變更。 > 如果您在解決衝突時遇到問題,該[影片](https://www.youtube.com/watch?v=xNVM5UxlFSA)可以很好地解釋它。 流行的 Git 工作流程 ------------ ![git 工作流程](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x955re263jtueig35kyg.png) 存在各種 Git 工作流程,但需要注意的是,不存在通用的「最佳」Git 工作流程。相反,每種方法都有其自身的優點和缺點。讓我們來探索這些不同的工作流程,以了解它們的優點和缺點。 ![git 工作流程](https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExeTY0eTI3anV6YnJ3Y2Y3bzd6ZTE5dHJ6OG9hdDNsM3hwcW1ubHZiMCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/dSetNZo2AJfptAk9hp/giphy.gif) ### 功能分支工作流程🌱 每個新功能或錯誤修復都是在自己的分支中開發的,然後在完成後將其合併回主分支。 > - **優點**:隔離變更並減少衝突。 > - **弱點**:可能變得複雜並且需要勤奮的分行管理。 ### Gitflow 工作流程 🌊 Gitflow 定義了嚴格的分支模型,為不同類型的開發任務提供了預先定義的分支。 它包括長期分支,例如 main、develop、feature 分支、release 分支和 hotfix 分支。 > - **優點**:適合定期發布、長期維護的專案。 > - **缺點**:對於較小的團隊來說可能過於複雜 ### 分岔工作流程🍴 在此工作流程中,每個開發人員都會複製主儲存庫,但他們不會將變更直接推送到主儲存庫,而是將變更推送到自己的儲存庫分支。然後,開發人員建立拉取請求以提出對主儲存庫的更改,從而允許在合併之前進行程式碼審查和協作。 這是我們在開源 Glasskube 儲存庫上進行協作的工作流程。 > - **優點**:鼓勵外部貢獻者進行協作,而無需授予對主儲存庫的直接寫入存取權。 > - **弱點**:維持分支和主儲存庫之間的同步可能具有挑戰性。 ### 拉取請求工作流程 ⏩ 與分叉工作流程類似,但開發人員不是分叉,而是直接在主儲存庫中建立功能分支。 > - **優點**:促進團隊成員之間的程式碼審查、協作和知識共享。 > - **弱點**:對人類程式碼審查員的依賴可能會導致開發過程延遲。 ### 基於主幹的開發🪵 如果您所在的團隊專注於快速迭代和持續交付,您可能會使用基於主幹的開發,開發人員直接在主分支上工作,提交小而頻繁的變更。 > - **優勢**:促進快速迭代、持續集成,並專注於為生產提供小而頻繁的變更。 > - **缺點**:需要強大的自動化測試和部署管道來確保主分支的穩定性,可能不適合發佈時間表嚴格或功能開發複雜的專案。 ### 什麼叉子? 強烈建議在開源專案上進行分叉,因為您可以完全控制自己的儲存庫副本。您可以進行變更、嘗試新功能或修復錯誤,而不會影響原始專案。 > 💡 我花了很長時間才弄清楚,雖然分叉存儲庫作為單獨的實體開始,但它們保留了與原始存儲庫的連接。此連接可讓您追蹤原始專案中的變更並將您的分支與其他人所做的更新同步。 這就是為什麼即使您推送到原始存儲庫也是如此。您的變更也會顯示在遙控器上。 Git 備忘錄 ------- ``` # Clone a Repository git clone <repository_url> # Stage Changes for Commit git add <file(s)> # Commit Changes git commit -m "Commit message" # Push Changes to the Remote Repository git push # Force Push Changes (use with caution) git push --force # Reset Working Directory to Last Commit git reset --hard # Create a New Branch git branch <branch_name> # Switch to a Different Branch git checkout <branch_name> # Merge Changes from Another Branch git merge <branch_name> # Rebase Changes onto Another Branch (use with caution) git rebase <base_branch> # View Status of Working Directory git status # View Commit History git log # Undo Last Commit (use with caution) git reset --soft HEAD^ # Discard Changes in Working Directory git restore <file(s)> # Retrieve Lost Commit References git reflog # Interactive Rebase to Rearrange Commits git rebase --interactive HEAD~3 ``` --- 獎金!一些 Git 工具和資源可以讓您的生活更輕鬆。 -------------------------- - 互動式變基[工具](https://github.com/MitMaro/git-interactive-rebase-tool)。 - [Cdiff](https://github.com/amigrave/cdiff)查看豐富多彩的增量差異。 - 互動式 Git 分支[遊樂場](https://learngitbranching.js.org/?locale=en_US) --- 如果您喜歡這類內容並希望看到更多內容,請考慮在 GitHub 上給我們一個 Star 來支持我們🙏 [![連小貓也喜歡送星星](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzaxhc3f53sggz7v3bw4.jpeg)](https://github.com/glasskube/glasskube) --- 原文出處:https://dev.to/glasskube/the-guide-to-git-i-never-had-1450

如何讓您的網站離線工作🌐

> 了解更多:- https://codexdindia.blogspot.com/2024/04/how-to-make-your-website-work-offline.html > 範例網站:- https://sh20raj.github.io/offline-website/ 和原始碼:- https://github.com/SH20RAJ/offline-website 和[文章](https://dev.to/sh20raj/building-an-offline-enabled-to-do-list-web-app-89j) 那麼,您想讓您的網站即使在網路決定休息時也能正常運作嗎?就像 YouTube 如何讓您在沒有 Wi-Fi 的時刻下載影片⛱️ 一樣,您也可以對您的網站執行同樣的操作,即使在網路玩捉迷藏時也可以存取它。讓我們深入研究建立一個像值得信賴的助手一樣的網站,它始終為您的用戶提供服務,即使處於離線狀態也是如此。我們將使用**HTML5 遊戲**的範例 😚 因為,嘿,誰不喜歡好遊戲,對吧? 🎮 ### 為什麼你需要線下的好處 首先,讓我們談談為什麼擁有一個離線就緒的網站會改變遊戲規則。想像一下:不穩定的網路、偏遠地區或只是不穩定的連線 – 並不是每個人都能獲得流暢、不間斷的網路流量。透過為您的用戶提供離線選項,您可以確保他們仍然可以盡情享受您的內容,無論他們是在野外還是在飛機上。這一切都是為了提升使用者體驗! 🚀 ### 如何讓您的網站成為線下冠軍 #### 1.**與服務人員友好相處**: 將 Service Worker 視為網站離線表演的後台工作人員。他們就像您網站的保鏢,決定在網路中斷時顯示哪些內容。 - **註冊您的 Service Worker** :將此腳本放入您網站的 HTML 中以使事情順利進行: ``` <script> if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/service-worker.js') .then(function(registration) { console.log('Service Worker registered with scope:', registration.scope); }).catch(function(error) { console.error('Service Worker registration failed:', error); }); } </script> ``` - **快取好東西**:在您的 Service Worker 檔案 ( `service-worker.js` ) 中,儲存您想要離線使用的東西: ``` var CACHE_NAME = 'my-website-cache-v1'; var urlsToCache = [ '/', '/styles/main.css', '/scripts/main.js', '/images/logo.png' ]; self.addEventListener('install', function(event) { event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { console.log('Opened cache'); return cache.addAll(urlsToCache); }) ); }); ``` - **離線播放**:當您的使用者嘗試離線存取某些內容時,Service Worker 會介入以挽救局面: ``` self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { if (response) { return response; } return fetch(event.request); }) ); }); ``` #### 2.**使用離線內容開始遊戲**: 對於 HTML5 遊戲或任何其他需要離線執行的內容,請確保您已準備好所有元件。這意味著快取 HTML、CSS、JavaScript、圖片 – 基本上,您的遊戲順利執行所需的一切。 #### 3.**下載功能(為什麼不呢?)** : 就像您可以在 YouTube 上下載貓影片一樣,您可以讓用戶直接從您的網站下載您的遊戲檔案: ``` <a href="/path/to/game.zip" download>Download Game</a> ``` ### 測試和改進 - **測試時間**:在您放鬆身心之前,先嘗試您的離線魔法。 Chrome DevTools 的應用程式面板是您的好夥伴 - 使用它來測試您的網站離線時的行為並進行任何調整。 - **優化派對**:為了獲得額外的魅力,請考慮延遲加載資源並明智地使用快取。如果您的網站稍後需要趕上伺服器,您甚至可以加入一些後台同步。 ### 包起來🎁 即使沒有網路,讓您的網站成為一個放鬆的聚會場所也是雙贏的。用戶可以隨時隨地深入了解您的內容,無需網路。透過引入 Service Worker、快取必需的內容,甚至可能加入下載功能,您正在為出色的離線體驗奠定基礎。因此,繼續吧,給您的用戶離線擊掌,讓您的網站成為他們的首選,即使在網路小睡時也是如此。 🌟 --- {% 發布 https://dev.to/sh20raj/introducing-encriptorjs-secure-text-encryption-and-decryption-in-javascript-a-jwt-easy-to-use-alternative-l02 %} --- 原文出處:https://dev.to/sh20raj/how-to-make-your-website-used-without-internet-3e3l

如何亂下 git 讓自己被公司開除

這是比利。 ----- ![帶著微笑和紅色領帶的簡筆畫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zi8n22y9i5j499h2bvx7.png) 他是一位為重要公司工作的實習開發人員。 對公司來說不幸的是,今天比利醒來並選擇了*暴力。* 這是因為他覺得學習Git非常麻煩、枯燥、很費解。 分支、提交、簽出、HEAD、功能、暫存,天啊! 這對他來說實在太多了。 但隨後比利想到了一個絕對是最好、最壞的主意。 > 「如果我學習 git 時先學會什麼不該做,然後又去做,那會怎麼樣!” 這將完成三件事: 1. 他會透過給自己一些通常被禁止的有趣的小挑戰來學習 git 最常用的工具。 2. 如果他知道什麼**不該**做,那麼他以後就可以專注於他**應該**做的事情。 3. 這樣的學習滿足了他混亂的邪惡傾向。 對比利來說,這聽起來越來越像是個好主意。這肯定會讓他成為一個更好的開發人員。 但只有一個問題...... ### Git 是開發人員用來管理軟體原始碼的版本控制系統。 每當某人更改、新增甚至刪除某些內容時,Git 都會記錄誰做了什麼。 如果你想在你工作的公司擁有的儲存庫中做一些非常糟糕的事情,那麼總是有人可以追溯到你。 那肯定會讓你被解僱。 這就是比利偷了特倫特電腦的原因。 ![簡筆人物比利舉著一台逼真的筆記型電腦,上面寫著“特倫特的電腦(被盜)”](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4dgqmz1otq6yqcqj3vsf.png) 特倫特是個大笨蛋,他去洗手間時打開了電腦,而且沒有採取任何保護措施。 在上個月的聚會後,他還沒有事先詢問就吃了最後一片披薩。 透過 Trent 的計算機,Billy 現在可以存取相同的儲存庫,但需要使用 Trent 的登入憑證。 所以現在 Billy 可以透過先學習他不應該做的所有事情來學習 Git,例如: 1.使用--force將程式碼推送到別人的分支 ----------------------- 假設目前的 git 生態系如下所示: ![主分支和同事功能分支的 Git 圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d6jhhy9i977la225uatn.png) Billy 目前正在查看另一位同事分支的早期版本。 如果兩個人在同一個分支上簽出,但其中一個人開始將變更推送到遠端,則可能會發生這種情況。 這意味著比利在分支上落後了。如果他想取得目前所在分支的最新更改,他會在終端機中寫入`git pull` 有趣的事實: Git pull 其實是另外 2 個 git 指令的組合。 - `git fetch origin` (取得遠端的最新變更而不檢查或合併它) - `git merge origin/<branch name>` (這*會將*本機變更合併至遠端。由於通常您不會合併本機文件,因此 git 會執行所謂的「快轉」操作,最終您會得到最新的變更) 比利想知道如果他嘗試推動這個人的分支會發生什麼,即使他落後於最新的變化。 通常,如果他嘗試`git push`某些程式碼,該嘗試將會失敗並出現錯誤 - 要求他首先提取最新的更改。 (這是 git 內建的安全網,以避免工作遺失。除非先拉,否則無法推!) 但如果比利執行`git push --force`指令,就可以避免這種情況。 `git push --force`對於開發人員來說通常是一個大問題。這是一個強制覆蓋 git 歷史記錄並讓您推送本地更改的命令,儘管它可能會刪除同一分支上其他人的工作。 比利以前從未使用過它,是一個好奇的男孩,所以他做了任何好奇的人都會做的事情。 1. 他建立了一個新文件,其中包含特殊文字: `echo "Trent was here" > Trent.txt` 2. 他對分行做出了非常重要的改變 `git add Trent.txt` `git commit -m "Trent committed this"` 這使得 git 看起來像這樣: ![Git 流程圖顯示了他的同事的更改如何消失以及 Billy 的新程式碼如何覆蓋它](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3wzzbao8zv2mbs9ciuqy.png) 3. 他透過強制將新變更推送到分支來結束 `git push --force` 幾秒鐘後... *噗!* Billy 非常重要的更改現在已在 Git 中! 同時,他同事的所有工作完全消失了! 天啊,那真是太有趣了。比利想知道他還要等多久才能讓那位同事注意到。 他想知道是否有什麼事情是他能做的最糟糕的事情。也許……他可以在生產中做類似的事情? 比利腦中的一個燈泡突然熄滅了!如果他做了: 2.生產分支上的硬重置 ----------- `Git reset`是一個命令,類似於 Billy 對他的同事所做的那樣,撤消在分支中建立的對先前提交的更改。 與他之前學到的`git push --force`指令不同,沒有什麼可以推送的。它只是透過(通常)取消提交在某個提交之前完成的所有事情來重寫 git 歷史記錄。 git reset 指令有 3 種模式。 1. `git reset --soft`將 HEAD(Head 是您目前簽出的提交)移回指定的提交,同時也撤銷所做的所有變更。所有這些變更都會返回暫存狀態,並允許您再次提交。 2. `git reset --mixed`與`git reset --soft`作用相同,但會保留您所做的所有變更。這也是 git reset 指令的預設模式。因此,如果您編寫`git reset` ,則與執行`git reset --mixed`相同。 3. `git reset --hard`是惡魔般的。它不會撤消更改並將其保留在暫存/未暫存狀態...它只是丟棄它們。 *噗* 當您硬重置到舊提交時,所有這些更改都會消失。 因此,如果 Billy 說…硬重置到**6 個月前**的提交,哦,我不知道,這對公司來說將是非常糟糕的。 比利微笑著打開終端機。 記住 git 生態系統是什麼樣子的: ![Git 分支顯示 6 個月前的提交和最新的提交](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4xwvqa9275q5f4f9oa1p.png) 比利高興地開始說: 1. 在終端`git checkout main`中輸入,將他定位到該分支的最新提交。 2. 使用 git 視覺化工具從主分支尋找 6 個月前的提交。 3. 最後輸入`git reset --hard <commit hash>`刪除主分支中過去 6 個月的所有變更。 幾秒鐘後... *噗!* 比利成功地讓一些公司高層非常非常生氣! 但等一下... 比利能夠做到這一點很奇怪,不是嗎?畢竟... ### 權限通常在儲存庫中設置,以便任何人都無法直接推送到生產分支。 這可以防止意外推送或重寫直接影響網站的 git 歷史記錄。 這就是為什麼存在所謂的「拉取請求」(或 PR)的原因。 ### 拉取請求是將一組變更從一個分支合併到另一個分支的提議。 通常,其他精通技術的開發人員首先必須接受您的更改,然後您才能合併。 但如果從未設定這些權限會發生什麼事? 好吧,似乎像比利這樣的人可以在一秒鐘內抹掉每個人過去兩個季度的努力。 他計算出,在他對生產產生主要影響之前,他可能還有 10 分鐘……不,15 分鐘。 所以比利必須快速行動。在一個名叫特倫特的人陷入麻煩之前,他可能還有時間去做另一件混亂的邪惡事情。 該怎麼辦... 哦,比利知道!他應該: 3. 揭露專案秘密並將其推向生產! ----------------- Billy 可以透過修改 .gitignore 檔案輕鬆完成此操作。 ### .gitignore 是位於專案目錄中的一種特殊類型的檔案。顧名思義,它指定 Git 應忽略哪些檔案並避免讓您暫存。 當您有一些不想先上傳到儲存庫的特定檔案時,這非常有用。 您*通常*希望避免上傳的檔案之一是 .env 檔案。 ### .env 檔案往往在專案中用於保存您將在整個解決方案中使用的環境變數。 它們具有鍵/值對以及您*確實*不想上傳的資訊。 API 金鑰、資料庫 URI、AUTH 金鑰等。 但比利不喜歡保守秘密。 他是他故事中的英雄,必須讓人知道! 因此,如果我們假設 .gitignore 檔案如下所示: ``` # Javascript node_modules node_modules/ # API keys .env ``` 那麼比利要做的就是: 1. 找到 .gitignore 文件 2. 使用他最喜歡的 IDE 或終端文字編輯器從檔案中刪除 .env 行並儲存。 (這使得文件現在看起來像這樣) ``` # Javascript node_modules node_modules/ # API keys are gone from ignore oops ``` 3. 將現在更改的 .gitignore 檔案新增到暫存中。 Billy 透過在終端機中輸入`git add .gitignore`來完成此操作 4. 等一下!不要忘記 - 由於 Git 現在不會忽略 .env 文件,Billy 也必須加入它! `git add .env`也被輸入到終端機中。 5. 是時候做出承諾了!比利用這一行做到了這一點: ``` `git commit -m "FREEEEEEDOOOOOMMM!!!! #TrentWasHere"` ``` 6. 最後一步!是時候推送到主分支了。再次,由於某種原因,沒有任何權限設定可以阻止比利,他可以在終端機中寫入`git push --force` 。 幾秒鐘後... *噗!* 「自由、平等、博愛」比利高興地低聲說!就在他把特倫特的電腦留在了它所屬的地方。 這也是一件好事,因為他剛剛聽到遠處房間裡傳來廁所沖水的聲音。 比利跑回他的辦公桌,在任何人注意到之前及時趕到。 *唷* 看來特倫特終於從衛浴休息回來,坐在辦公桌前。 但就在他打開筆記型電腦之前,特倫特的電話響了。 *戒指戒指,戒指戒指* 比利滿懷期待地等待著,看到特倫特慢慢地拿起電話。 “你好?” “特倫特。辦公室。現在。” 比利可以在 5 個辦公桌外聽到特倫特電話裡的喊叫聲。 “哇,老闆發生什麼事了?” … “我沒有做任何事——” … 「你們生產出了什麼事嗎? … “我正在路上” 崔恩特迅速跑向辦公室,可能是為了他一生中的尖叫聲。 比利坐下來,放鬆下來,終於可以說: 「今天我是一個更好的開發人員」。 ![簡筆畫比利微笑著](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7627w4yj05yxqwiomyty.png) --- 這是我寫過的最愚蠢的文章。 ------------- 如果您喜歡我的幽默感,那麼我想您一定會喜歡我的電子報「Exceptional Frontend」——網路上最有趣的前端電子報。 它適合任何想要一份以前端為中心、試圖與其他人不同的時事通訊的開發人員。我們專注於使其獨一無二,最重要的是—有趣! 同時也幫助開發人員在他們所做的事情上變得出色。 [您可以在這裡註冊。](https://exceptional-frontend.aweb.page/p/b56d0522-222b-468d-85b2-d69c15afac1c) --- 原文出處:https://dev.to/mauroaccorinti/how-to-get-somebody-fired-using-git-31if

初級開發人員會犯什麼錯誤

詢問高級開發人員 -------- ![問](https://i.imgur.com/ZRJAQRB.gif) 我們最近在[Reddit](https://www.reddit.com/r/webdev/comments/112im2m/senior_devs_what_are_the_most_damaging/)上的網頁開發社群向資深開發人員詢問了以下問題: *初級開發人員中最具破壞性的誤解是什麼?* 我們想知道初級開發人員一直犯的錯誤是什麼,以及他們可以做些什麼來改進。令人驚訝的是,我們詢問的高級開發人員給了我們大量的回應——準確地說超過 270 個! 由於這裡有很多有價值的訊息,我們決定在本文中總結回應。 所以,請閱讀一下,然後在評論中告訴我們您的想法:) 最常見的主題 ------ 回覆中有很多很棒的具體例子,但我們注意到其中有很多共同的主題: - **程式碼品質** - **管理時間和期望** - **有效的溝通和團隊合作** 這些似乎是高階開發人員最常談論的話題。這是有道理的——當你深入問題的核心時,這些事情幾乎可以成就或毀掉*任何*職業。 有趣的是,最受歡迎的回覆是涵蓋所有這些主題的問題。例如,以下是得票最高的回覆: ![稍後清理](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j6rrl9weufsl2ch92myk.png) 先質量,後速度 ------- > *高程式碼品質只會間接影響使用者。主要目的是維持較高的開發速度,使所有利害關係人受益* > — **zoechi** \* r/webdev 在「品質」辯論中,實際上存在兩個陣營,其中一些認為品質程式碼是關於: 1. 編寫乾淨、可讀的程式碼,易於維護 2. 編寫按時交付且有效的程式碼。 滿足最後期限、發布功能和編寫最佳程式碼之間的平衡顯然是一個棘手的問題。 有些人認為,業務現實意味著團隊通常沒有時間進行乾淨的程式碼模式。最重要的一點是按時完成任務並讓客戶滿意。 另一方面,許多高級開發人員認為品質程式碼應該是**優先事項**,並且透過將其作為優先事項,您實際上可以提高長期速度,即使無法滿足短期期限。 ![您不必接觸所有程式碼](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3z5qolwgu1y09gut2sp9.png) 不過,這種討論可能會分散初級開發人員優先事項的注意力,這些優先事項是作為開發人員成長和改進,而不是帶領團隊取得成功。因此,**我們認為初級開發人員最好先專注於質量,然後再提高交付速度。** --- 順便說一句,我們正在建立[Wasp](https://wasp-lang.dev) ,一個具有超能力的全端 React + NodeJS 框架,成為提升全端 Web 開發人員技能的最佳方法之一。 透過[在 GitHub 上為我們的儲存庫加註星標,](https://www.github.com/wasp-lang/wasp)您將幫助我們繼續使 Web 開發變得更快、更輕鬆,並每週為您帶來這樣的內容。 ![https://media1.giphy.com/media/ZfK4cXKJTTay1Ava29/giphy.gif?cid=7941fdc6pmqo30ll0e4rzdiisbtagx97sx5t0znx4lk0auju&ep=v1_gifs_searchx97sx5t0znx4lk0auju&ep=v1_gifs_search}&ridgi.](https://media1.giphy.com/media/ZfK4cXKJTTay1Ava29/giphy.gif?cid=7941fdc6pmqo30ll0e4rzdiisbtagx97sx5t0znx4lk0auju&ep=v1_gifs_search&rid=giphy.gif&ct=g) <https://www.github.com/wasp-lang/wasp> ⭐️ 感謝您的支持🙏 --- 保持謙虛並管理期望 --------- 作為初級開發人員,您不會期望第一次就能把所有事情都做對。 人們假設您會隨著時間的推移學習最佳實踐,但在此過程中您可能會產生不一致的工作、犯錯,甚至可能會破壞一些東西。 ![愚蠢的](https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExYWZ3bHZ0NXZ1NzFtbTR4djc3dTJhZ2E0dGtyZHpod2FnNDVleDBrcCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/xT9Igi8GqJpYgC2vQs/giphy.gif) 但沒關係。 這是過程的一部分。這是預期的。重要的是要記住,這並不反映您作為工程師或個人的價值或價值。 在回覆中,也有許多開發者認識到另一個開發者希望“稍後修復問題”,以此來消除對其工作的批評。他們普遍認為這是一種壞習慣,因為即使開發人員獲得了更多經驗,這也常常困擾著他們。 例如,「程式碼審查不應該針對個人」是高階開發人員的共同觀點。 因此,**能夠優雅地接受批評是一項需要培養的重要技能。** 畢竟,前輩會根據他們自己的經驗指導你做出更好的決定。青少年也在那裡學習。 ![資深開發人員並不了解一切](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l3j4lng6hbhwc7hpopmc.png) 但是您應該多久尋求一位前輩的建議呢?你應該照他們所說的去做,還是按照某些人在 YouTube 或某些博文中告訴你的那樣*去做 x 的唯一方法*;)? 你是否應該在每次陷入困境時尋求幫助,還是應該犧牲自己的理智,獨自掙扎數日? 嗯,這取決於你問誰。但大多數回應都明確表示: 1. 你應該先自己嘗試一下。 2. 使用您可用的資源(ChatGPT、Stack Overflow、Google)嘗試找出答案。 3. 一旦你進展緩慢,就尋求幫助。 4. 如果你有一個可能的解決方案,而且它與高級開發人員的建議不同,這並不意味著它是錯誤的——有時可能有很多可能的方法來實現相同的目標! ![提問打擾前輩](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e7yylsti2jhtcc81fv93.png) 保持靈活性並樂於改變 ---------- 沒有什麼比科技世界的變化更快。作為開發人員,您需要不斷學習和適應新技術和趨勢。如果您不喜歡改變,那麼軟體開發人員可能不適合您。 ![一切都比你想像的還要長](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rkvo1a6gavuj0d341h9y.png) 除了事物不斷變化之外,這種工作還會挑戰你的假設。例如,您認為可能是最佳的解決方案結果與您團隊的預期目標或最終產品不相容,您被迫使用「次優」解決方案。 為什麼?因為這可能是最好的方法 考慮到團隊的限制來完成工作。 ( *「抱歉,朋友,我們不能在這個框架上使用您最喜歡的框架。」* ) **保持靈活和開放思想的**開發人員通常在這方面具有優勢。 他們對特定技術或方法不太教條,更願意適應當前的情況。他們通常比同齡人進步得更快,並且能夠出色地完成工作。 --- 如果到目前為止您發現這很有用,**請[在 GitHub 上給我們一顆星](https://github.com/wasp-lang/wasp)以表示您的支持**!它將幫助我們繼續製造更多類似的東西。 ![https://res.cloudinary.com/practicaldev/image/fetch/s--OCpry2p9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads /文章/bky8z46ii7ayejprrqw3.gif](https://res.cloudinary.com/practicaldev/image/fetch/s--OCpry2p9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_800/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bky8z46ii7ayejprrqw3.gif) <https://www.github.com/wasp-lang/wasp> ⭐️ 感謝您的支持🙏 --- 所以你怎麼看? ------- 好的,這就是我們的總結。 ![開發商](https://media2.giphy.com/media/v1.Y2lkPTc5MGI3NjExMjc2ZzRreTgzMm45ZjZudXMxYXl6ZWVvYmV4eG5sZDdvZXg1dGFjNyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/l3q2zbskZp2j8wniE/giphy.gif) 對於這些意見,你有何看法?高階開發人員的評估是否正確,或者他們是否遺漏了某些內容? 您最近是否意識到一些您希望早點知道的事情?如果是的話,請在評論中與我們分享! --- 噓!我和我的同事也在下面的 YouTube 影片中更詳細地討論了結果並權衡了我們的意見。所以檢查一下,如果這是你的事情:) https://www.youtube.com/watch?v=eermNn9VhOA --- 原文出處:https://dev.to/wasp/what-junior-devs-get-wrong-an8

React 元件設計模式 - 第 1 部分

React 設計模式是開發人員用來解決使用 React 建立應用程式時遇到的常見問題和挑戰的既定實踐和解決方案。這些模式封裝了針對重複出現的設計問題的可重複使用解決方案,從而提高了可維護性、可擴展性和效率。它們提供了一種結構化的方法來組織元件、管理狀態、處理資料流和最佳化效能。 **請考慮以下 6 種 React 設計模式:** 1. 容器和呈現模式 2. HOC(高階元件)模式 3. 複合元件模式 4. 提供者模式(使用提供者進行資料管理) 5. 狀態減速器模式 6. 元件組成模式 1. 容器和呈現模式 ---------- 在此模式中,容器元件負責管理資料和狀態邏輯。它們從外部來源獲取資料,在必要時對其進行操作,並將其作為 props 傳遞給展示元件。它們通常連接到外部服務、Redux 儲存或上下文提供者。 另一方面,展示元件僅專注於 UI 元素的展示。他們透過 props 從容器元件接收資料,並以視覺上吸引人的方式呈現它。展示元件通常是無狀態的功能元件或純元件,這使得它們更容易測試和重複使用。 **讓我們考慮一個複雜的範例來說明這些模式:** 假設我們正在建立一個社群媒體儀表板,用戶可以在其中查看朋友的貼文並與他們互動。以下是我們建立元件的方式: **容器元件(FriendFeedContainer):** 該元件將負責從 API 獲取有關好友貼文的資料、處理任何必要的資料轉換以及管理提要的狀態。它將相關資料傳遞給展示元件。 ``` import React, { useState, useEffect } from 'react'; import FriendFeed from './FriendFeed'; const FriendFeedContainer = () => { const [friendPosts, setFriendPosts] = useState([]); useEffect(() => { // Fetch friend posts from API const fetchFriendPosts = async () => { const posts = await fetch('https://api.example.com/friend-posts'); const data = await posts.json(); setFriendPosts(data); }; fetchFriendPosts(); }, []); return <FriendFeed posts={friendPosts} />; }; export default FriendFeedContainer; ``` **展示元件(FriendFeed):** 該元件將從其父容器元件 (FriendFeedContainer) 接收好友貼文資料作為 props,並以視覺上吸引人的方式呈現它們。 ``` import React from 'react'; const FriendFeed = ({ posts }) => { return ( <div> <h2>Friend Feed</h2> <ul> {posts.map(post => ( <li key={post.id}> <p>{post.content}</p> <p>Posted by: {post.author}</p> </li> ))} </ul> </div> ); }; export default FriendFeed; ``` 透過以這種方式建立我們的元件,我們將獲取資料和管理狀態的問題與 UI 渲染邏輯分開。這種分離使得我們的 React 應用程式在擴充時可以更輕鬆地進行測試、重複使用和維護。 2.HOC(高階元件)模式 ------------- 高階元件 (HOC) 是 React 中的一種模式,可讓您跨多個元件重複使用元件邏輯。它們是接受元件並傳回具有附加功能的新元件的函數。 為了示範 HOC 在具有 React hook 的社群媒體儀表板範例中的使用,讓我們考慮一個場景,其中您有多個元件需要從 API 取得使用者資料。您可以建立一個 HOC 來處理資料獲取並將獲取的資料作為 props 傳遞給包裝的元件,而不是在每個元件中重複取得邏輯。 這是一個基本範例: ``` import React, { useState, useEffect } from 'react'; // Define a higher-order component for fetching user data const withUserData = (WrappedComponent) => { return (props) => { const [userData, setUserData] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { // Simulate fetching user data from an API const fetchData = async () => { try { const response = await fetch('https://api.example.com/user'); const data = await response.json(); setUserData(data); setLoading(false); } catch (error) { console.error('Error fetching user data:', error); setLoading(false); } }; fetchData(); }, []); return ( <div> {loading ? ( <p>Loading...</p> ) : ( <WrappedComponent {...props} userData={userData} /> )} </div> ); }; }; // Create a component to display user data const UserProfile = ({ userData }) => { return ( <div> <h2>User Profile</h2> {userData && ( <div> <p>Name: {userData.name}</p> <p>Email: {userData.email}</p> {/* Additional user data fields */} </div> )} </div> ); }; // Wrap the UserProfile component with the withUserData HOC const UserProfileWithUserData = withUserData(UserProfile); // Main component where you can render the wrapped component const SocialMediaDashboard = () => { return ( <div> <h1>Social Media Dashboard</h1> <UserProfileWithUserData /> </div> ); }; export default SocialMediaDashboard; ``` 在這個例子中: - `withUserData`是一個高階元件,用於處理從 API 取得使用者資料。它包裝傳遞的元件 ( `WrappedComponent` ) 並將取得的使用者資料作為 prop ( `userData` ) 提供給它。 - `UserProfile`是一個功能元件,它接收`userData`屬性並顯示使用者設定檔資訊。 - `UserProfileWithUserData`是透過使用`withUserData`包裝`UserProfile`傳回的元件。 - `SocialMediaDashboard`是主要元件,您可以在其中呈現`UserProfileWithUserData`或任何其他需要使用者資料的元件。 使用此模式,您可以輕鬆地跨社交媒體儀表板應用程式中的多個元件重複使用資料取得邏輯,而無需重複程式碼。 3. 複合元件模式 --------- React 中的複合元件模式是一種設計模式,可讓您建立協同工作以形成有凝聚力的 UI 的元件,同時仍保持明確的關注點分離並提供自訂元件行為和外觀的靈活性。 在此模式中,父元件充當一個或多個子元件(稱為「複合元件」)的容器。這些子元件協同工作以實現特定的功能或行為。複合元件的關鍵特徵是它們透過父元件彼此共享狀態和功能。 以下是使用 hooks 在 React 中實作複合元件模式的簡單範例: ``` import React, { useState } from 'react'; // Parent component that holds the compound components const Toggle = ({ children }) => { const [isOn, setIsOn] = useState(false); // Function to toggle the state const toggle = () => { setIsOn((prevIsOn) => !prevIsOn); }; // Clone the children and pass the toggle function and state to them const childrenWithProps = React.Children.map(children, (child) => { if (React.isValidElement(child)) { return React.cloneElement(child, { isOn, toggle }); } return child; }); return <div>{childrenWithProps}</div>; }; // Child component for the toggle button const ToggleButton = ({ isOn, toggle }) => { return ( <button onClick={toggle}> {isOn ? 'Turn Off' : 'Turn On'} </button> ); }; // Child component for the toggle status const ToggleStatus = ({ isOn }) => { return <p>The toggle is {isOn ? 'on' : 'off'}.</p>; }; // Main component where you use the compound components const App = () => { return ( <Toggle> <ToggleStatus /> <ToggleButton /> </Toggle> ); }; export default App; ``` 在這個例子中: - `Toggle`是保存複合元件( `ToggleButton`和`ToggleStatus` )的父元件。 - `ToggleButton`是負責渲染切換按鈕的子元件。 - `ToggleStatus`是另一個負責顯示切換狀態的子元件。 - `Toggle`元件管理狀態 ( `isOn` ) 並提供`toggle`功能來控制狀態。它克隆其子級並將`isOn`狀態和`toggle`函數作為 props 傳遞給它們。 透過使用複合元件模式,您可以建立可重複使用和可組合的元件,封裝複雜的 UI 邏輯,同時仍允許自訂和靈活性。 ### 4. Provider Pattern(使用Provider進行資料管理) React 中的提供者模式是一種設計模式,用於跨多個元件管理和共用應用程式狀態或資料。它涉及建立一個封裝狀態或資料的提供者元件,並透過 React 的上下文 API 將其提供給其後代元件。 讓我們透過一個範例來說明 React 中用於管理使用者身份驗證資料的 Provider 模式: ``` // UserContext.js import React, { createContext, useState } from 'react'; // Create a context for user data const UserContext = createContext(); // Provider component export const UserProvider = ({ children }) => { const [user, setUser] = useState(null); // Function to login user const login = (userData) => { setUser(userData); }; // Function to logout user const logout = () => { setUser(null); }; return ( <UserContext.Provider value={{ user, login, logout }}> {children} </UserContext.Provider> ); }; export default UserContext; ``` 在這個例子中: - 我們使用 React 的`createContext`函數來建立一個名為`UserContext`上下文。此上下文將用於跨元件共享用戶資料和與身份驗證相關的功能。 - 我們定義一個`UserProvider`元件作為`UserContext`的提供者。該元件使用`useState`鉤子管理使用者狀態,並提供`login`和`logout`等方法來更新使用者狀態。 - 在`UserProvider`內部,我們用`UserContext.Provider`包裝`children` ,並將`user`狀態以及`login`和`logout`函數作為提供者的值傳遞。 - 現在,任何需要存取使用者資料或驗證相關功能的元件都可以使用`useContext`掛鉤來使用`UserContext` 。 讓我們建立一個使用上下文中的使用者資料的元件: ``` // UserProfile.js import React, { useContext } from 'react'; import UserContext from './UserContext'; const UserProfile = () => { const { user, logout } = useContext(UserContext); return ( <div> {user ? ( <div> <h2>Welcome, {user.username}!</h2> <button onClick={logout}>Logout</button> </div> ) : ( <div> <h2>Please log in</h2> </div> )} </div> ); }; export default UserProfile; ``` 在此元件中: 我們匯入`UserContext`並使用`useContext`鉤子來存取`UserProvider`提供的使用者資料和`logout`功能。 根據使用者是否登錄,我們呈現不同的 UI 元素。 最後,我們用`UserProvider`包裝我們的應用程式,以使用戶資料和身份驗證相關的功能可供所有元件使用: ``` // App.js import React from 'react'; import { UserProvider } from './UserContext'; import UserProfile from './UserProfile'; const App = () => { return ( <UserProvider> <div> <h1>My App</h1> <UserProfile /> </div> </UserProvider> ); }; export default App; ``` 透過這種方式,Provider 模式允許我們跨多個元件管理和共享應用程式狀態或資料,而無需進行 prop 鑽取,從而使我們的程式碼更乾淨、更易於維護。 --- 原文出處:https://dev.to/fpaghar/react-component-design-patterns-part-1-5f0g

使用 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

加入我們的第一個社群挑戰:前端挑戰

--- 標題:加入我們的第一個社群挑戰:前端挑戰 發表:真實 標籤: frontendchallenge, devchallenge, css, javascript 封面圖:https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jfwaylumsyrf5t3upl4v.jpg --- 我們很高興推出我們的**第一個官方[開發挑戰賽](https://dev.to/devteam/introducing-dev-challenges-1mk9)**:前端挑戰賽! 這項挑戰將持續到 3 月 31 日,這將是一個展示您的創造力、建立您的個人資料、贏得徽章的機會,總的來說,您將獲得很多樂趣。 對於第一個挑戰,我們有三個提示 -**您可以只參加一個或全部三個**。也歡迎在同一提示下多次提交,但請務必遵循我們的提交指南。 對於本次挑戰,每個提示都會有一名獲勝者。獲獎者將獲得專屬 DEV 榮譽徽章以及[DEV 商店](https://shop.forem.com)贈送的禮物。有效提交的參與者將獲得完成徽章。 繼續閱讀以了解每個提示以及如何參與! 提示 -- *仔細閱讀這些提示,然後使用模板提交挑戰。* ### CSS 藝術挑戰賽🎨 把你最喜歡的零食變成 CSS 藝術作品,讓我們驚嘆不已。 您提交的內容**不應使用任何 JavaScript** ,並且應在 CSS 中發揮您的創造力,並且看起來應該很美味。您提交的內容將包括標記,可能包括 SVG 等,但主要應該*展示*您的 CSS 技能。 這是供任何想要直接參與的人使用的提交模板,但請在提交之前查看所有評審標準、挑戰規則以及[官方挑戰頁面](https://dev.to/challenges/frontend)上的常見問題: {% cta https://dev.to/new?prefill=---%0Atitle%3A%20%0Apublished%3A%20false%0Atags%3A%20frontendchallenge%2C%20devchallenge%2C%20css%0A---% 0A%0A\_This%20is%20a%20submission%20for%20DEV%20Challenge%20v24.03.20%2C%20CSS%20Art%3A%20Favorite%20Snack.\_%0A%0A%23%3A%20Favorite%20Snack.\_%0A%0A%23%3pi%202323pi7%20A%3pi%C% 21--%20What%20snack%20are%20you%20highlighting%20today%3F%20--%3E%0A%0A%23%23%20Demo%0A%3C%21--%20Show%20us%20your%20CSS% 20Art!%20You%20can%20直接%20embed%20an%20editor%20into%20this%20post%20(參見%20the%20FAQ%20section%20of%20the%20challenge%20page)%20%2000%20%20you 20an% 20image%20of%20your%20project%20and%20share%20a%20public%20link%20to%20the%20code.%20--%3E%0A%0A%23%23%20Journey%0A%3%21 %20告訴%20us%20about%20your%20process%2C%20what%20you%20learned%2C%20anything%20you%20are%20尤其%20proud%20of%2C%20what%20you%20hope%20proud%20of%2C%20what%20you%20hope%20to% %20etc.% 20--%3E%0A%0A%3C%21--%20團隊%20Submissions%3A%20請%20pick%20one%20member%20to%20publish%20the%20submission%20and%20ammacredit 20by%20listing%20their% 20DEV%20usernames%20直接%20in%20the%20body%20of%20the%20post。%20--%3E%0A%0A%3C%21--%20我們%20鼓勵%20you% 20to%20考慮%20加入%20a%20許可證%20for%20your%20code.%20--%3E%0A%0A%3C%21--%20Don%27t%20忘記%20to%20add%20a% 20cover%20image%20to%20your%20post%20(if% 20你%20想要)。%20--%3E%0A%0A%0A%3C%21--%20感謝%20%20參與!% 20--%3E %} CSS 藝術挑戰提交模板 {% 結束%} --- ### 讓我的標記更迷人💅 使用 CSS 和 JavaScript 使下面的入門 HTML 標記美觀、互動且有用。 您提交的內容應該比我們提供的 HTML 更有趣、更具互動性,而且也應該可用且易於存取。**您不應該直接編輯提供的 HTML,除非它是在程式中透過 JavaScript 功能進行編輯的。**最終結果應該可以改進現有的預期功能。我們期待風格*和*實質。 ***入門 HTML*** ``` <section id="camp-activities-inquiry"> <h1>Camp Activities Inquiry</h1> <form action="/submit-form" method="POST"> <label for="activity-select">Which camp activities are you most looking forward to?</label> <select id="activity-select" name="activity"> <option value="">--Please choose an option--</option> <option value="hiking">Hiking</option> <option value="canoeing">Canoeing</option> <option value="fishing">Fishing</option> <option value="crafts">Crafts</option> <option value="archery">Archery</option> </select> <label for="food-allergies">Food Allergies (if any)</label> <textarea id="food-allergies" name="food_allergies" rows="4" cols="50"></textarea> <label for="additional-info">Additional things the counselor should know</label> <textarea id="additional-info" name="additional_info" rows="4" cols="50"></textarea> <button type="submit">Submit</button> </form> </section> ``` 這是供任何想要直接參與的人使用的提交模板,但請在提交之前查看所有評審標準、挑戰規則以及[官方挑戰頁面](https://dev.to/challenges/frontend)上的常見問題: {% cta https://dev.to/new?prefill=---%0Atitle%3A%20%0Apublished%3A%20false%0Atags%3A%20frontendchallenge%2C%20devchallenge%2C%20css%2C%endchallenge%2C%20devchallenge%2C%20css%2C%20javascript%0A ---%0A%0A\_This%20is%20a%20submission%20for%20DEV%20Challenge%20v24.03.20%2C%20Glam%20Up%20My%20Markup%3A%20Camp%20Activities\_%A% 20I%20Built%0A%3C%21--%20告訴%20us%20什麼%20you%20built%20和%20what%20you%20是%20look%20to%20實現。%20--%3E%0A% 0A%23%23 %20Demo%0A%3C%21--%20Show%20us%20your%20project!%20You%20can%20直接%20embed%20an%20editor%20into%20this%20postthe%20this%20post20( 20FAQ%20section%20from% 20%20挑戰%20頁)%20或%20you%20can%20share%20an%20image%20of%20your%20project%20和%20share%20a%20037% 20碼。%20--%3E%0A% 0A%23%23%20旅程%0A%3C%21--%20告訴%20us%20about%20your%20process%2C%20what%20you%20learned%2C% 20anything%20you%20are%20specially%20proud%20of%2C% 20what%20you%20hope%20to%20do%20next%2C%20etc.%20--%3E%0A%0A%3C%21%20etc.%20--%3E%0A%0A%3C%21%200ams %3A%20Please%20pick%20one%20member%20to%20publish %20the%20submission%20and%20credit%20teammates%20by%20listing%20他們的%20DEV%20usernames%20直接7% 20post。%20--%3E%0A%0A%3C%21- -%20我們%20鼓勵%20you%20to%20考慮%20為%20您的%20程式碼加入%20a%20許可證%20 .%20--%3E%0A%0A%3C%21--%20不要%27t%20忘記%20to%20add %20a%20cover%20image%20to%20your%20post%20(如果%20you%20想要)。%20--%3E%0A%0A%0A%3C%21--%20感謝%20%20的參與!%20- -%3E%} 使我的標記提交模板更加迷人 {% 結束%} --- ### 一位元組解釋器✍️ 用**256 個或更少的字元**解釋瀏覽器 API 或功能。 選擇任何瀏覽器 API(例如“fetch”、“DOM”、“Geolocation”)並*簡要*解釋它的作用,也許它是如何工作的,以及為什麼有人可能會使用它。您有 256 個字元(比一條推文還少)來表達您的觀點,因此挑戰在於*保持簡單*。 你無法用 256 個字元涵蓋所有細節,但你能挑出最重要的嗎?只要符合請求的精神,我們在這裡對*API 或功能*的定義是靈活的。 這是供任何想要直接參與的人使用的提交模板,但請在提交之前查看所有評審標準、挑戰規則以及[官方挑戰頁面](https://dev.to/challenges/frontend)上的常見問題: {% cta https://dev.to/new?prefill=---%0Atitle%3A%20%0Apublished%3A%20false%0Atags%3A%20frontendchallenge%2C%20devchallenge%2C%20javascript%2C%endchallenge%2C%20devchallenge%2C%20javascript%2C%20webdev%0A ---%0A%0A\_This%20is%20a%20submission%20for%20DEV%20Challenge%20v24.03.20%2C%20One%20Byte%20Explainer%3A%20Browser%20API%20Byte%20Explainer%3A%20Browser%20API%20or% 23%20解釋%0A%3C%21--%20解釋%20a%20瀏覽器%20API%20or%20feature%20in%20256%20字元%20或%20less。%20--%3E%0A%0A %23%23%20附加%20Context%0A%3C%21--%20請%20share%20any%20additional%20context%20you%20think%20the%20judges%20should%20take%20into%20sideity% %20to%20your%20One%20Byte %20解釋者。%20--%3E%0A%0A%3C%21--%20團隊%20Submissions%3A%20請%20pick%20one%20member%20to%20publish% 20the%20submission%20and%20credit%20teammates%20by% 20列出%20他們的%20DEV%20用戶名%20直接%20in%20the%20body%20of%20the%20post。%20--%3E%0A% 0A%3C%21--%20Don%27t%20forget%20to%20add%20a %20cover%20image%20to%20your%20post%20(如果%20you%20想要)。%20--%3E%0A% 0A%0A%3C%21--%20感謝%20%20的參與!%20--% 3E%} 一字節解釋提交模板 {% 結束%} --- 如何參與 ---- 為了參與,您需要使用提示的提交範本發布貼文。 **您可以在[官方挑戰頁面](https://dev.to/challenges/frontend)上找到所有評審標準、官方挑戰規則(即資格)、我們的常見問題解答等,因此請務必仔細閱讀。** {% cta https://dev.to/challenges/frontend %} 官方挑戰頁面 {% 結束%} 重要的日子 ----- - 3 月 20 日:前端挑戰 v24.03.20 開始! - 3 月 31 日:提交截止時間為太平洋夏令時間晚上 11:59 - 4 月 2 日:公佈得獎者 - 4 月 3 日:敬請期待我們的下一個挑戰 我們很高興看到誰最終能在我們的第一個挑戰中獲得吹噓的權利!問題?請在下面詢問他們。 祝你好運,編碼愉快! --- 原文出處:https://dev.to/devteam/join-our-first-community-challenge-the-frontend-challenge-8be

useReducer() 優於 useState() 的 3 個理由

這是什麼 ---- `useReducer()`是 React Hooks API 中的一個方法,與`useState`類似,但為您提供了更多控制權來管理狀態。它接受一個reducer函數和初始狀態作為參數,並傳回狀態和調度方法: ``` const [state, dispatch] = React.useReducer(reducerFn, initialState, initFn); ``` reducer(之所以這樣稱呼,是因為您將傳遞給陣列方法`Array.prototype.reduce(reducer, initialValue)`函數類型)是取自 Redux 的模式。如果您不熟悉 Redux,簡而言之,reducer 是一個純函數,它將先前的狀態和操作作為參數,並傳回下一個狀態。 ``` (prevState, action) => newState ``` 操作是描述發生的事情的一條訊息,並且根據該訊息,reducer 指定狀態應如何變更。動作透過`dispatch(action)`方法傳遞。 使用它的 3 個理由 ---------- 大多數時候,您只需使用`useState()`方法就可以了,該方法建立在`useReducer()`之上。但有些情況下`useReducer()`較可取。 ### 下一個狀態取決於上一個狀態 當狀態依賴前一個方法時,使用此方法總是更好。它會給你一個更可預測的狀態轉換。簡單的例子是: ``` function reducer(state, action) { switch (action.type) { case 'ADD': return { count: state.count + 1 }; case 'SUB': return { count: state.count - 1 }; default: return state; } } function Counter() { const [state, dispatch] = React.useReducer(reducer, { count: 0 }); return ( <> Count: {state.count} <button onClick={() => dispatch({type: 'ADD'})}>Add</button> <button onClick={() => dispatch({type: 'SUB'})}>Substract</button> </> ); } ``` ### 複雜狀態形狀 當狀態包含多個原始值時,例如巢狀物件或陣列。例如: ``` const [state, dispatch] = React.useReducer( fetchUsersReducer, { users: [ { name: 'John', subscribred: false }, { name: 'Jane', subscribred: true }, ], loading: false, error: false, }, ); ``` 管理這種本地狀態更容易,因為參數相互依賴,並且所有邏輯都可以封裝到一個reducer中。 ### 易於測試 reducer是純函數,這意味著它們沒有副作用,並且在給定相同參數的情況下必須返回相同的結果。測試它們更容易,因為它們不依賴 React。讓我們從計數器範例中取得一個reducer並使用模擬狀態對其進行測試: ``` test("increments the count by one", () => { const newState = reducer({ count: 0 }, { type: "ADD" }); expect(newState.count).toBe(1) }) ``` 結論 -- `useReducer()`是`useState()`的替代方法,它使您可以更好地控制狀態管理並使測試更容易。所有情況都可以使用`useState()`方法來完成,因此總而言之,使用您熟悉的方法,並且對您和同事來說更容易理解。 --- 原文出處:https://dev.to/spukas/3-reasons-to-usereducer-over-usestate-43ad

建立文字到 PowerPoint 應用程式(LangChain、Next.js 和 CopilotKit)

長話短說 ==== 在本文中,您將學習如何建立由 AI 驅動的 PowerPoint 應用程式,該應用程式可以搜尋網路以自動製作有關任何主題的簡報。 我們將介紹使用: - 用於應用程式框架的 Next.js 🖥️ - 法學碩士 OpenAI 🧠 - LangChain 和 Tavily 的網路搜尋人工智慧代理🤖 - 使用 CopilotKit 將 AI 整合到您的應用程式中 🪁 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ztokmi3hdcthmxkj2gny.gif) --- CopilotKit:為您的應用程式建立人工智慧副駕駛 --------------------------- CopilotKit 是[開源人工智慧副駕駛平台。](https://github.com/CopilotKit/CopilotKit)我們可以輕鬆地將強大的人工智慧整合到您的 React 應用程式中。 建造: - ChatBot:上下文感知的應用內聊天機器人,可以在應用程式內執行操作 💬 - CopilotTextArea:人工智慧驅動的文字字段,具有上下文感知自動完成和插入功能📝 - 聯合代理:應用程式內人工智慧代理,可以與您的應用程式和使用者互動🤖 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h69i50cxsyvcknlcs6q0.gif) {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} 現在回到文章。 (本文是我們三週前發表的一篇文章的進展,但您無需閱讀該文章即可理解這一點)。 --- **先決條件** -------- 在開始建立應用程式之前,讓我們先查看建置應用程式所需的依賴項或套件 `copilotkit/react-core` :CopilotKit 前端包,帶有 React hooks,用於向副駕駛提供應用程式狀態和操作(AI 功能) `copilotkit/react-ui` :聊天機器人側邊欄 UI 的 CopilotKit 前端包 `copilotkit/react-textarea` :CopilotKit 前端包,用於在演講者筆記中進行人工智慧輔助文字編輯。 `LangChainJS` :一個用於開發由語言模型支援的應用程式的框架。 `Tavily Search API` :幫助將法學碩士和人工智慧應用程式連接到可信賴的即時知識的 API。 安裝所有專案包和依賴項 ----------- 在安裝所有專案包和依賴項之前,我們首先在終端機上執行以下命令來建立 Nextjs 專案。 ``` npx create-next-app@latest ``` 然後系統會提示您選擇一些選項。請隨意標記它們,如下所示。 ![建立 Nextjs 專案](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n668ixcvu5lnrsm9jpmq.png) 之後,使用您選擇的文字編輯器開啟新建立的 Nextjs 專案。然後在命令列中執行以下命令來安裝所有專案包和依賴項。 ``` npm i @copilotkit/backend @copilotkit/shared @langchain/langgraph @copilotkit/react-core @copilotkit/react-ui @copilotkit/react-textarea @heroicons/react ``` **建立 PowerPoint 應用程式前端** ------------------------ 讓我們先建立一個名為`Slide.tsx`的檔案。該文件將包含顯示和編輯投影片內容的程式碼,包括其`title` 、 `body text` 、 `background image`和`spoken narration text` 。 要建立該文件,請前往`/[root]/src/app`並建立一個名為`components`的資料夾。在 Components 資料夾中,建立`Slide.tsx`檔案。 之後,在文件頂部加入以下程式碼。程式碼定義了兩個名為`SlideModel`和`SlideProps`的 TypeScript 介面。 ``` "use client"; // Define an interface for the model of a slide, specifying the expected structure of a slide object. export interface SlideModel { title: string; content: string; backgroundImageDescription: string; spokenNarration: string; } // Define an interface for the properties of a component or function that manages slides. export interface SlideProps { slide: SlideModel; partialUpdateSlide: (partialSlide: Partial<SlideModel>) => void; } ``` 接下來,在上面的程式碼下面加入以下程式碼。程式碼定義了一個名為`Slide`功能元件,它接受`SlideProps`類型的 props。 ``` // Define a functional component named Slide that accepts props of type SlideProps. export const Slide = (props: SlideProps) => { // Define a constant for the height of the area reserved for speaker notes. const heightOfSpeakerNotes = 150; // Construct a URL for the background image using the description from slide properties, dynamically fetching an image from Unsplash. const backgroundImage = 'url("https://source.unsplash.com/featured/?' + encodeURIComponent(props.slide.backgroundImageDescription) + '")'; // Return JSX for the slide component. return ( <> {/* Slide content container with dynamic height calculation to account for speaker notes area. */} <div className="w-full relative bg-slate-200" style={{ height: `calc(100vh - ${heightOfSpeakerNotes}px)`, // Calculate height to leave space for speaker notes. }} > {/* Container for the slide title with centered alignment and styling. */} <div className="h-1/5 flex items-center justify-center text-5xl text-white text-center z-10" > {/* Textarea for slide title input, allowing dynamic updates. */} <textarea className="text-2xl bg-transparent text-black p-4 text-center font-bold uppercase italic line-clamp-2 resize-none flex items-center" style={{ border: "none", outline: "none", }} value={props.slide.title} placeholder="Title" onChange={(e) => { props.partialUpdateSlide({ title: e.target.value }); }} /> </div> {/* Container for the slide content with background image. */} <div className="h-4/5 flex" style={{ backgroundImage, backgroundSize: "cover", backgroundPosition: "center", }} > {/* Textarea for slide content input, allowing dynamic updates and styled for readability. */} <textarea className="w-full text-3xl text-black font-medium p-10 resize-none bg-red mx-40 my-8 rounded-xl text-center" style={{ lineHeight: "1.5", }} value={props.slide.content} placeholder="Body" onChange={(e) => { props.partialUpdateSlide({ content: e.target.value }); }} /> </div> </div> {/* Textarea for entering spoken narration with specified height and styling for consistency. */} <textarea className=" w-9/12 h-full bg-transparent text-5xl p-10 resize-none bg-gray-500 pr-36" style={{ height: `${heightOfSpeakerNotes}px`, background: "none", border: "none", outline: "none", fontFamily: "inherit", fontSize: "inherit", lineHeight: "inherit", }} value={props.slide.spokenNarration} onChange={(e) => { props.partialUpdateSlide({ spokenNarration: e.target.value }); }} /> </> ); }; ``` 之後,我們現在會建立一個名為`Presentation.tsx`的檔案。 該文件將包含初始化和更新投影片狀態、渲染目前投影片以及根據目前狀態動態啟用或停用按鈕實現導覽和投影片管理操作的程式碼。 要建立該文件,請將另一個文件新增至元件資料夾中,並將其命名為`Presentation.tsx` ,然後使用下列程式碼在檔案頂部匯入`React hooks` 、 `icons` 、 `SlideModel`和`Slide`元件。 ``` "use client"; import { useCallback, useMemo, useState } from "react"; import { BackwardIcon, ForwardIcon, PlusIcon, SparklesIcon, TrashIcon } from "@heroicons/react/24/outline"; import { SlideModel, Slide } from "./Slide"; ``` 之後,在上面的程式碼下面加入以下程式碼。程式碼定義了一個`ActionButton`功能元件,它將呈現具有可自訂屬性的按鈕元素。 ``` export const ActionButton = ({ disabled, onClick, className, children, }: { disabled: boolean; onClick: () => void; className?: string; children: React.ReactNode; }) => { return ( <button disabled={disabled} className={`bg-blue-500 text-white font-bold py-2 px-4 rounded ${disabled ? "opacity-50 cursor-not-allowed" : "hover:bg-blue-700"} ${className}`} onClick={onClick} > {children} </button> ); }; ``` 然後在上面的程式碼下面加入下面的程式碼。程式碼定義了一個名為「Presentation」的功能元件,用於初始化投影片的狀態並定義一個用於更新目前投影片的函數。 ``` // Define the Presentation component as a functional component. export const Presentation = () => { // Initialize state for slides with a default first slide and a state to track the current slide index. const [slides, setSlides] = useState<SlideModel[]>([ { title: `Welcome to our presentation!`, // Title of the first slide. content: 'This is the first slide.', // Content of the first slide. backgroundImageDescription: "hello", // Description for background image retrieval. spokenNarration: "This is the first slide. Welcome to our presentation!", // Spoken narration text for the first slide. }, ]); const [currentSlideIndex, setCurrentSlideIndex] = useState(0); // Current slide index, starting at 0. // Use useMemo to memoize the current slide object to avoid unnecessary recalculations. const currentSlide = useMemo(() => slides[currentSlideIndex], [slides, currentSlideIndex]); // Define a function to update the current slide. This function uses useCallback to memoize itself to prevent unnecessary re-creations. const updateCurrentSlide = useCallback( (partialSlide: Partial<SlideModel>) => { // Update the slides state by creating a new array with the updated current slide. setSlides((slides) => [ ...slides.slice(0, currentSlideIndex), // Copy all slides before the current one. { ...slides[currentSlideIndex], ...partialSlide }, // Merge the current slide with the updates. ...slides.slice(currentSlideIndex + 1), // Copy all slides after the current one. ]); }, [currentSlideIndex, setSlides] // Dependencies for useCallback. ); // The JSX structure for the Presentation component. return ( <div className="relative"> {/* Render the current slide by passing the currentSlide and updateCurrentSlide function as props. */} <Slide slide={currentSlide} partialUpdateSlide={updateCurrentSlide} /> {/* Container for action buttons located at the top-left corner of the screen. */} <div className="absolute top-0 left-0 mt-6 ml-4 z-30"> {/* Action button to add a new slide. Disabled state is hardcoded to true for demonstration. */} <ActionButton disabled={true} onClick={() => { // Define a new slide object. const newSlide: SlideModel = { title: "Title", content: "Body", backgroundImageDescription: "random", spokenNarration: "The speaker's notes for this slide.", }; // Update the slides array to include the new slide. setSlides((slides) => [ ...slides.slice(0, currentSlideIndex + 1), newSlide, ...slides.slice(currentSlideIndex + 1), ]); // Move to the new slide by updating the currentSlideIndex. setCurrentSlideIndex((i) => i + 1); }} className="rounded-r-none" > <PlusIcon className="h-6 w-6" /> {/* Icon for the button. */} </ActionButton> {/* Another action button, currently disabled and without functionality. */} <ActionButton disabled={true} onClick={async () => { }} // Placeholder async function. className="rounded-l-none ml-[1px]" > <SparklesIcon className="h-6 w-6" /> {/* Icon for the button. */} </ActionButton> </div> {/* Container for action buttons at the top-right corner for deleting slides, etc. */} <div className="absolute top-0 right-0 mt-6 mr-24"> <ActionButton disabled={slides.length === 1} // Disable button if there's only one slide. onClick={() => {}} // Placeholder function for the button action. className="ml-5 rounded-r-none" > <TrashIcon className="h-6 w-6" /> {/* Icon for the button. */} </ActionButton> </div> {/* Display current slide number and total slides at the bottom-right corner. */} <div className="absolute bottom-0 right-0 mb-20 mx-24 text-xl" style={{ textShadow: "1px 1px 0 #ddd, -1px -1px 0 #ddd, 1px -1px 0 #ddd, -1px 1px 0 #ddd", }} > Slide {currentSlideIndex + 1} of {slides.length} {/* Current slide and total slides. */} </div> {/* Container for navigation buttons (previous and next) at the bottom-right corner. */} <div className="absolute bottom-0 right-0 mb-6 mx-24"> {/* Button to navigate to the previous slide. */} <ActionButton className="rounded-r-none" disabled={ currentSlideIndex === 0 || true} // Example condition to disable button; 'true' is just for demonstration. onClick={() => { setCurrentSlideIndex((i) => i - 1); // Update currentSlideIndex to move to the previous slide. }} > <BackwardIcon className="h-6 w-6" /> {/* Icon for the button. */} </ActionButton> {/* Button to navigate to the next slide. */} <ActionButton className="mr-[1px] rounded-l-none" disabled={ true || currentSlideIndex + 1 === slides.length} // Example condition to disable button; 'true' is just for demonstration. onClick={async () => { setCurrentSlideIndex((i) => i + 1); // Update currentSlideIndex to move to the next slide. }} > <ForwardIcon className="h-6 w-6" /> {/* Icon for the button. */} </ActionButton> </div> </div> ); }; ``` 要在瀏覽器上呈現 PowerPoint 應用程式,請前往`/[root]/src/app/page.tsx`檔案並新增以下程式碼。 ``` "use client"; import "./style.css"; import { Presentation } from "./components/Presentation"; export default function AIPresentation() { return ( <Presentation /> ); } ``` 如果您想要在 Powerpoint 應用程式前端新增樣式,請在`/[root]/src/app`資料夾中建立名為`style.css`的檔案。 然後導航[到此 gist 文件](https://gist.github.com/TheGreatBonnie/e7c0b790a2e2af3e669810539ba54fed),複製 CSS 程式碼,並將其新增至 style.css 檔案。 最後,在命令列上執行命令`npm run dev` ,然後導航到 http://localhost:3000/。 現在您應該在瀏覽器上查看 PowerPoint 應用程式,如下所示。 ![PowerPoint應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqcjqqmo1b2oow6y4p76.png) **將 PowerPoint 應用程式與 CopilotKit 後端集成** -------------------------------------- 讓我們先在根目錄中建立一個名為`.env.local`的檔案。然後在保存 ChatGPT 和 Tavily Search API 金鑰的檔案中加入下面的環境變數。 ``` OPENAI_API_KEY="Your ChatGPT API key" TAVILY_API_KEY="Your Tavily Search API key" ``` 若要取得 ChatGPT API 金鑰,請導覽至 https://platform.openai.com/api-keys。 ![ChatGPT API 金鑰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1u65aswytyym0zpoh5wx.png) 若要取得 Tavilly Search API 金鑰,請導覽至 https://app.tavily.com/home ![泰維利搜尋 API 金鑰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ugx1oqifnk24l69jjkf.png) 之後,轉到`/[root]/src/app`並建立一個名為`api`的資料夾。在`api`資料夾中,建立一個名為`copilotkit`的資料夾。 在`copilotkit`資料夾中,建立一個名為`research.ts`的檔案。然後導航到[該 Research.ts gist 文件](https://gist.github.com/TheGreatBonnie/58dc21ebbeeb8cbb08df665db762738c),複製程式碼,並將其新增至**`research.ts`**檔案中 接下來,在`/[root]/src/app/api/copilotkit`資料夾中建立一個名為`route.ts`的檔案。該文件將包含設定後端功能來處理 POST 請求的程式碼。它有條件地包括對給定主題進行研究的“研究”操作。 現在在文件頂部導入以下模組。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; // For backend functionality with CopilotKit. import { researchWithLangGraph } from "./research"; // Import a custom function for conducting research. import { AnnotatedFunction } from "@copilotkit/shared"; // For annotating functions with metadata. ``` 在上面的程式碼下面,定義一個執行時環境變數和一個註解的函數,以便使用下面的程式碼進行研究。 ``` // Define a runtime environment variable, indicating the environment where the code is expected to run. export const runtime = "edge"; // Define an annotated function for research. This object includes metadata and an implementation for the function. const researchAction: AnnotatedFunction<any> = { name: "research", // Function name. description: "Call this function to conduct research on a certain topic. Respect other notes about when to call this function", // Function description. argumentAnnotations: [ // Annotations for arguments that the function accepts. { name: "topic", // Argument name. type: "string", // Argument type. description: "The topic to research. 5 characters or longer.", // Argument description. required: true, // Indicates that the argument is required. }, ], implementation: async (topic) => { // The actual function implementation. console.log("Researching topic: ", topic); // Log the research topic. return await researchWithLangGraph(topic); // Call the research function and return its result. }, }; ``` 然後在上面的程式碼下加入下面的程式碼來定義處理POST請求的非同步函數。 ``` // Define an asynchronous function that handles POST requests. export async function POST(req: Request): Promise<Response> { const actions: AnnotatedFunction<any>[] = []; // Initialize an array to hold actions. // Check if a specific environment variable is set, indicating access to certain functionality. if (process.env["TAVILY_API_KEY"]) { actions.push(researchAction); // Add the research action to the actions array if the condition is true. } // Instantiate CopilotBackend with the actions defined above. const copilotKit = new CopilotBackend({ actions: actions, }); // Use the CopilotBackend instance to generate a response for the incoming request using an OpenAIAdapter. return copilotKit.response(req, new OpenAIAdapter()); } ``` **將 PowerPoint 應用程式與 CopilotKit 前端集成** -------------------------------------- 讓我們先導入`/[root]/src/app/components/Slide.tsx`檔案頂部的`useMakeCopilotActionable`掛鉤。 ``` import { useMakeCopilotActionable } from "@copilotkit/react-core"; ``` 在 Slide 函數中,新增以下程式碼,該程式碼使用`useMakeCopilotActionable`掛鉤來設定一個名為`updateSlide`的操作,該操作具有特定參數以及根據提供的值更新投影片的實作。 ``` useMakeCopilotActionable({ // Defines the action name. This is a unique identifier for the action within the application. name: "updateSlide", // Describes what the action does. In this case, it updates the current slide. description: "Update the current slide.", // Details the arguments that the action accepts. Each argument has a name, type, description, and a flag indicating if it's required. argumentAnnotations: [ { name: "title", // The argument name. type: "string", // The data type of the argument. description: "The title of the slide. Should be a few words long.", // Description of the argument. required: true, // Indicates that this argument must be provided for the action to execute. }, { name: "content", type: "string", description: "The content of the slide. Should generally consists of a few bullet points.", required: true, }, { name: "backgroundImageDescription", type: "string", description: "What to display in the background of the slide. For example, 'dog', 'house', etc.", required: true, }, { name: "spokenNarration", type: "string", description: "The spoken narration for the slide. This is what the user will hear when the slide is shown.", required: true, }, ], // The implementation of the action. This is a function that will be called when the action is executed. implementation: async (title, content, backgroundImageDescription, spokenNarration) => { // Calls a function passed in through props to partially update the slide with new values for the specified properties. props.partialUpdateSlide({ title, content, backgroundImageDescription, spokenNarration, }); }, }, [props.partialUpdateSlide]); // Dependencies array for the custom hook or function. This ensures that the action is re-initialized only when `props.partialUpdateSlide` changes. ``` 之後,請前往`/[root]/src/app/components/Presentation.tsx`檔案並使用下面的程式碼匯入頂部的 CopilotKit 前端套件。 ``` import { useCopilotContext } from "@copilotkit/react-core"; import { CopilotTask } from "@copilotkit/react-core"; import { useMakeCopilotActionable, useMakeCopilotReadable } from "@copilotkit/react-core"; ``` 在演示函數中,加入以下程式碼,該程式碼使用`useMakeCopilotReadable`掛鉤加入`Slides`和`currentSlide`幻燈片陣列作為應用程式內聊天機器人的上下文。掛鉤使副駕駛可以讀取簡報中的整個幻燈片集合以及當前幻燈片的資料。 ``` useMakeCopilotReadable("These are all the slides: " + JSON.stringify(slides)); useMakeCopilotReadable( "This is the current slide: " + JSON.stringify(currentSlide) ); ``` 在`useMakeCopilotReadable`掛鉤下方,新增以下程式碼,該程式碼使用`useCopilotActionable`掛鉤來設定名為`appendSlide`的操作,其中包含說明和加入多張幻燈片的實作函數。 ``` useMakeCopilotActionable( { // Defines the action's metadata. name: "appendSlide", // Action identifier. description: "Add a slide after all the existing slides. Call this function multiple times to add multiple slides.", // Specifies the arguments that the action takes, including their types, descriptions, and if they are required. argumentAnnotations: [ { name: "title", // The title of the new slide. type: "string", description: "The title of the slide. Should be a few words long.", required: true, }, { name: "content", // The main content or body of the new slide. type: "string", description: "The content of the slide. Should generally consist of a few bullet points.", required: true, }, { name: "backgroundImageDescription", // Description for fetching or generating the background image of the new slide. type: "string", description: "What to display in the background of the slide. For example, 'dog', 'house', etc.", required: true, }, { name: "spokenNarration", // Narration text that will be read aloud during the presentation of the slide. type: "string", description: "The text to read while presenting the slide. Should be distinct from the slide's content, and can include additional context, references, etc. Will be read aloud as-is. Should be a few sentences long, clear, and smooth to read.", required: true, }, ], // The function to execute when the action is triggered. It creates a new slide with the provided details and appends it to the existing slides array. implementation: async (title, content, backgroundImageDescription, spokenNarration) => { const newSlide: SlideModel = { // Constructs the new slide object. title, content, backgroundImageDescription, spokenNarration, }; // Updates the slides state by appending the new slide to the end of the current slides array. setSlides((slides) => [...slides, newSlide]); }, }, [setSlides] // Dependency array for the hook. This action is dependent on the `setSlides` function, ensuring it reinitializes if `setSlides` changes. ); ``` 在上面的程式碼下方,定義一個名為`context`的變數,該變數使用名為`useCopilotContext`的自訂掛鉤從 copilot 上下文中檢索當前上下文。 ``` const context = useCopilotContext(); ``` 之後,定義一個名為`generateSlideTask`的函數,它包含一個名為`CopilotTask`的類別。 `CopilotTask`類別定義用於產生與簡報的整體主題相關的新投影片的指令 ``` const generateSlideTask = new CopilotTask({ instructions: "Make the next slide related to the overall topic of the presentation. It will be inserted after the current slide. Do NOT carry any research", }); ``` 然後在上面的程式碼下面初始化一個名為`generateSlideTaskRunning`的狀態變數,預設值為false。 ``` const [generateSlideTaskRunning, **setGenerateSlideTaskRunning**] = useState(false); ``` 之後,使用下面的程式碼更新簡報元件中的操作按鈕,以透過新增、刪除和導覽投影片來新增動態互動。 ``` // The JSX structure for the Presentation component. return ( <div className="relative"> {/* Renders the current slide using a Slide component with props for the slide data and a method to update it. */} <Slide slide={currentSlide} partialUpdateSlide={updateCurrentSlide} /> {/* Container for action buttons positioned at the top left corner of the relative parent */} <div className="absolute top-0 left-0 mt-6 ml-4 z-30"> {/* ActionButton to add a new slide. It is disabled when a generateSlideTask is running to prevent concurrent modifications. */} <ActionButton disabled={generateSlideTaskRunning} onClick={() => { const newSlide: SlideModel = { title: "Title", content: "Body", backgroundImageDescription: "random", spokenNarration: "The speaker's notes for this slide.", }; // Inserts the new slide immediately after the current slide and updates the slide index to point to the new slide. setSlides((slides) => [ ...slides.slice(0, currentSlideIndex + 1), newSlide, ...slides.slice(currentSlideIndex + 1), ]); setCurrentSlideIndex((i) => i + 1); }} className="rounded-r-none" > <PlusIcon className="h-6 w-6" /> </ActionButton> {/* ActionButton to generate a new slide based on the current context, also disabled during task running. */} <ActionButton disabled={generateSlideTaskRunning} onClick={async () => { setGenerateSlideTaskRunning(true); // Indicates the task is starting. await generateSlideTask.run(context); // Executes the task with the current context. setGenerateSlideTaskRunning(false); // Resets the flag when the task is complete. }} className="rounded-l-none ml-[1px]" > <SparklesIcon className="h-6 w-6" /> </ActionButton> </div> {/* Container for action buttons at the top right, including deleting the current slide and potentially other actions. */} <div className="absolute top-0 right-0 mt-6 mr-24"> {/* ActionButton for deleting the current slide, disabled if a task is running or only one slide remains. */} <ActionButton disabled={generateSlideTaskRunning || slides.length === 1} onClick={() => { console.log("delete slide"); // Removes the current slide and resets the index to the beginning as a simple handling strategy. setSlides((slides) => [ ...slides.slice(0, currentSlideIndex), ...slides.slice(currentSlideIndex + 1), ]); setCurrentSlideIndex((i) => 0); }} className="ml-5 rounded-r-none" > <TrashIcon className="h-6 w-6" /> </ActionButton> </div> {/* Display showing the current slide index and the total number of slides. */} <div className="absolute bottom-0 right-0 mb-20 mx-24 text-xl" style={{ textShadow: "1px 1px 0 #ddd, -1px -1px 0 #ddd, 1px -1px 0 #ddd, -1px 1px 0 #ddd", }} > Slide {currentSlideIndex + 1} of {slides.length} </div> {/* Navigation buttons to move between slides, disabled based on the slide index or if a task is running. */} <div className="absolute bottom-0 right-0 mb-6 mx-24"> {/* Button to move to the previous slide, disabled if on the first slide or a task is running. */} <ActionButton className="rounded-r-none" disabled={generateSlideTaskRunning || currentSlideIndex === 0} onClick={() => { setCurrentSlideIndex((i) => i - 1); }} > <BackwardIcon className="h-6 w-6" /> </ActionButton> {/* Button to move to the next slide, disabled if on the last slide or a task is running. */} <ActionButton className="mr-[1px] rounded-l-none" disabled={generateSlideTaskRunning || currentSlideIndex + 1 === slides.length} onClick={async () => { setCurrentSlideIndex((i) => i + 1); }} > <ForwardIcon className="h-6 w-6" /> </ActionButton> </div> </div> ); ``` 現在讓我們轉到`/[root]/src/app/page.tsx`文件,使用下面的程式碼匯入 CopilotKit 前端包和文件頂部的樣式。 ``` import { CopilotKit, } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; import "@copilotkit/react-ui/styles.css"; import "@copilotkit/react-textarea/styles.css"; ``` 然後使用`CopilotKit`和`CopilotSidebar`來包裝Presentation元件,如下所示。 ``` export default function AIPresentation() { return ( <CopilotKit url="/api/copilotkit/"> <CopilotSidebar instructions="Help the user create and edit a powerpoint-style presentation. IMPORTANT NOTE: SOMETIMES you may want to research a topic, before taking further action. BUT FIRST ASK THE USER if they would like you to research it. If they answer 'no', do your best WITHOUT researching the topic first." defaultOpen={true} labels={{ title: "Presentation Copilot", initial: "Hi you! 👋 I can help you create a presentation on any topic.", }} clickOutsideToClose={false} > <Presentation /> </CopilotSidebar> </CopilotKit> ); } ``` 之後,執行開發伺服器並導航到 http://localhost:3000/。您應該會看到應用程式內聊天機器人已整合到 PowerPoint Web 應用中。 ![應用程式內聊天機器人](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rb2g54qslrrfxyx2pbcy.png) 最後,給右側的聊天機器人一個提示,例如“在 JavaScript 上建立 PowerPoint 簡報”,聊天機器人將開始產生回應,完成後,使用底部的前進按鈕瀏覽產生的幻燈片。 注意:如果聊天機器人沒有立即產生投影片,請根據其回應給予適當的後續提示。 ![PowerPoint簡報](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v6dl4av0asoeokzopwra.png) 結論 -- 總而言之,您可以使用 CopilotKit 建立應用內 AI 聊天機器人,該機器人可以查看當前應用程式狀態並在應用程式內執行操作。 AI 聊天機器人可以與您的應用程式前端、後端和第三方服務對話。 完整的原始碼:https://github.com/TheGreatBonnie/aipoweredpowerpointapp --- 原文出處:https://dev.to/copilotkit/how-to-build-an-ai-powered-powerpoint-generator-langchain-copilotkit-openai-nextjs-4c76

30 個 JavaScript 奇妙小技巧

歡迎使用我們精選的 JavaScript 技巧集合,它將幫助您優化程式碼、使其更具可讀性並節省您的時間。 讓我們深入研究 JavaScript 的功能和超越傳統的技巧,並發現這種強大的程式語言的全部潛力。 ### 1. 使用!!轉換為布林值 使用雙重否定快速將任何值轉換為布林值。 ``` let truthyValue = !!1; // true let falsyValue = !!0; // false ``` ### 2. 預設功能參數 設定函數參數的預設值以避免未定義的錯誤。 ``` function greet(name = "Guest") { return `Hello, ${name}!`; } ``` ### 3. 短 if-else 的三元運算符 `if-else`語句的簡寫。 ``` let price = 100; let message = price > 50 ? "Expensive" : "Cheap"; ``` ### 4. 動態字串的範本文字 使用模板文字在字串中嵌入表達式。 ``` let item = "coffee"; let price = 15; console.log(`One ${item} costs $${price}.`); ``` ### 5. 解構賦值 輕鬆從物件或陣列中提取屬性。 ``` let [x, y] = [1, 2]; let {name, age} = {name: "Alice", age: 30}; ``` ### 6. 用於陣列和物件克隆的擴展運算符 克隆陣列或物件而不引用原始陣列或物件。 ``` let originalArray = [1, 2, 3]; let clonedArray = [...originalArray]; ``` ### 7. 短路評估 使用邏輯運算子進行條件執行。 ``` let isValid = true; isValid && console.log("Valid!"); ``` ### 8. 可選連結 (?.) 如果引用為`nullish`則可以安全地存取巢狀物件屬性,而不會出現錯誤。 ``` let user = {name: "John", address: {city: "New York"}}; console.log(user?.address?.city); // "New York" ``` ### 9. 空合併運算子 (??) 使用`??`為`null`或`undefined`提供預設值。 ``` let username = null; console.log(username ?? "Guest"); // "Guest" ``` [![monday.com 的互動式橫幅展示了在數位介面上組織工作流程任務的雙手,並帶有「告訴我如何做」號召性用語按鈕。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xd7qdmxdd726kskelydk.png)](https://try.monday.com/9xf9ftaa4i2f) ### 10. 使用`map` 、 `filter`和`reduce`進行陣列操作 無需傳統循環即可處理陣列的優雅方法。 ``` // Map let numbers = [1, 2, 3, 4]; let doubled = numbers.map(x => x * 2); // Filter const evens = numbers.filter(x => x % 2 === 0); // Reduce const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0); ``` ### 11.標記模板文字 使用模板文字進行函數呼叫以進行自訂字串處理。 ``` function highlight(strings, ...values) { return strings.reduce((prev, current, i) => `${prev}${current}${values[i] || ''}`, ''); } let price = 10; console.log(highlight`The price is ${price} dollars.`); ``` ### 12.使用Object.entries()和Object.fromEntries() 將物件轉換為陣列並返回以方便操作。 ``` let person = {name: "Alice", age: 25}; let entries = Object.entries(person); let newPerson = Object.fromEntries(entries); ``` ### 13. 唯一元素的集合物件 使用 Set 儲存任何類型的唯一值。 ``` let numbers = [1, 1, 2, 3, 4, 4]; let uniqueNumbers = [...new Set(numbers)]; ``` ### 14. 物件中的動態屬性名稱 在物件文字表示法中使用方括號來建立動態屬性名稱。 ``` let dynamicKey = 'name'; let person = {[dynamicKey]: "Alice"}; ``` ### 15. 使用bind()進行函數柯里化 建立一個新函數,在呼叫時將其 this 關鍵字設定為提供的值。 ``` function multiply(a, b) { return a * b; } let double = multiply.bind(null, 2); console.log(double(5)); // 10 ``` ### 16. 使用 Array.from() 從類別陣列物件建立陣列 將類似陣列或可迭代的物件轉換為真正的陣列。 ``` let nodeList = document.querySelectorAll('div'); let nodeArray = Array.from(nodeList); ``` ### 17. 可迭代物件的 for...of 循環 直接迭代可迭代物件(包括陣列、映射、集合等)。 ``` for (let value of ['a', 'b', 'c']) { console.log(value); } ``` ### 18. 使用 Promise.all() 實作並發 Promise 同時執行多個 Promise 並等待所有的都解決。 ``` let promises = [fetch(url1), fetch(url2)]; Promise.all(promises) .then(responses => console.log('All done')); ``` ### 19. 函數參數的剩餘參數 將任意數量的參數捕獲到陣列中。 ``` function sum(...nums) { return nums.reduce((acc, current) => acc + current, 0); } ``` [![Coursera Plus 訂閱產品包括 AWS 基礎、Google IT 支援專業憑證和商業網路安全專業化。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ys5gk2tfzcn4iniuq48s.png)](https://imp.i384100.net/c/3922519/1320997/14726) ### 20. 用於性能優化的記憶 儲存函數結果以避免冗餘處理。 ``` const memoize = (fn) => { const cache = {}; return (...args) => { let n = args[0]; // assuming single argument for simplicity if (n in cache) { console.log('Fetching from cache'); return cache[n]; } else { console.log('Calculating result'); let result = fn(n); cache[n] = result; return result; } }; }; ``` ### 21. 使用 ^ 交換值 使用 XOR 以位元運算子交換兩個變數的值,無需使用臨時變數。 ``` let a = 1, b = 2; a ^= b; b ^= a; a ^= b; // a = 2, b = 1 ``` ### 22. 使用 flat() 展平陣列 使用`flat()`方法輕鬆展平巢狀陣列,並將展平深度作為可選參數。 ``` let nestedArray = [1, [2, [3, [4]]]]; let flatArray = nestedArray.flat(Infinity); ``` ### 23. 用一元加法轉換為數字 使用一元加運算子快速將字串或其他值轉換為數字。 ``` let str = "123"; let num = +str; // 123 as a number ``` ### 24. HTML 片段的模板字串 使用模板字串建立 HTML 片段,使動態 HTML 生成更加清晰。 ``` let items = ['apple', 'orange', 'banana']; let html = `<ul>${items.map(item => `<li>${item}</li>`).join('')}</ul>`; ``` ### 25. 使用 Object.assign() 合併物件 將多個來源物件合併到一個目標物件中,有效地組合它們的屬性。 ``` let obj1 = { a: 1 }, obj2 = { b: 2 }; let merged = Object.assign({}, obj1, obj2); ``` [![符合人體工學的垂直滑鼠旨在減輕手腕壓力](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/56c0z4lzxtkthnnk8gsb.jpg)](https://amzn.to/3UXGIyx) 使用符合人體工學的滑鼠優化您的編程設置,專為舒適和長時間的編碼會話而定制。 ### 26. 預設值短路 處理潛在的未定義或空變數時,使用邏輯運算子指派預設值。 ``` let options = userOptions || defaultOptions; ``` ### 27. 使用括號表示法動態存取物件屬性 使用括號表示法動態存取物件的屬性,當屬性名稱儲存在變數中時非常有用。 ``` let property = "name"; let value = person[property]; // Equivalent to person.name ``` ### 28. 使用 Array.includes() 進行存在檢查 使用includes() 檢查陣列是否包含某個值,它是indexOf 的更清晰的替代方法。 ``` if (myArray.includes("value")) { // Do something } ``` ### 29. Function.prototype.bind() 的強大功能 將函數綁定到上下文(此值)並部分套用參數,以建立更多可重複使用和模組化的程式碼。 ``` const greet = function(greeting, punctuation) { return `${greeting}, ${this.name}${punctuation}`; }; const greetJohn = greet.bind({name: 'John'}, 'Hello'); console.log(greetJohn('!')); // "Hello, John!" ``` ### 30.防止物件修改 使用`Object.freeze()`防止物件進行修改,使其不可變。對於更深層的不變性,請考慮更徹底地強制不變性的函式庫。 ``` let obj = { name: "Immutable" }; Object.freeze(obj); obj.name = "Mutable"; // Fails silently in non-strict mode ``` 我希望這些 JavaScript 技巧為您提供如何進行[JavaScript 程式設計的](https://www.w3schools.com/js/)新視角。 從利用模板文字的簡潔功能到掌握`map` 、 `filter`和`reduce`的效率,這些 JavaScript 技巧將豐富您的開發工作流程並激發您的下一個專案。 讓這些 JavaScript 技巧不僅可以完善您目前的專案,還可以在您的[程式設計之旅](https://www.webdevstory.com/programming-roadmap/)中激發未來創新的靈感。 ***支持我們的技術見解*** [![請我喝杯咖啡](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lsm9uucbnw7x9iw0loxr.png)](https://www.buymeacoffee.com/mmainulhasan) [![透過 PayPal 按鈕捐贈](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ipnhbim2ba56kt32zhn3.png)](https://www.paypal.com/donate/?hosted_button_id=GDUQRAJZM3UR8) 注意:此頁面上的某些連結可能是附屬連結。如果您透過這些連結進行購買,我可能會賺取少量佣金,而無需您支付額外費用。感謝您的支持! --- 原文出處:https://dev.to/mmainulhasan/30-javascript-tricky-hacks-gfc

我正在建立一個全端應用程式:以下是我將要使用的庫......

您可以使用無數的框架和函式庫來改進您的全端應用程式。 我們將介紹令人興奮的概念,例如應用程式內通知、使用 React 製作影片、從為開發人員提供的電子郵件 API 到在瀏覽器中建立互動式音樂。 那我們就開始吧。 (不要忘記為這些庫加註星標以表示您的支持)。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qqoipyuoxgb83swyoo4a.gif) https://github.com/CopilotKit/CopilotKit --- 1. [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 在數小時內為您的產品提供 AI Copilot。 ------------------------------------------------------------------------------------ ![副駕駛套件](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzuxjfog2ldam3csrl62.png) 您可以使用兩個 React 元件將關鍵 AI 功能整合到 React 應用程式中。它們還提供內建(完全可自訂)Copilot 原生 UX 元件,例如`<CopilotKit />` 、 `<CopilotPopup />` 、 `<CopilotSidebar />` 、 `<CopilotTextarea />` 。 開始使用以下 npm 指令。 ``` npm i @copilotkit/react-core @copilotkit/react-ui @copilotkit/react-textarea ``` 這是整合 CopilotTextArea 的方法。 ``` import { CopilotTextarea } from "@copilotkit/react-textarea"; import { useState } from "react"; export function SomeReactComponent() { const [text, setText] = useState(""); return ( <> <CopilotTextarea className="px-4 py-4" value={text} onValueChange={(value: string) => setText(value)} placeholder="What are your plans for your vacation?" autosuggestionsConfig={{ textareaPurpose: "Travel notes from the user's previous vacations. Likely written in a colloquial style, but adjust as needed.", chatApiConfigs: { suggestionsApiConfig: { forwardedParams: { max_tokens: 20, stop: [".", "?", "!"], }, }, }, }} /> </> ); } ``` 您可以閱讀[文件](https://docs.copilotkit.ai/getting-started/quickstart-textarea)。 基本概念是在幾分鐘內建立可用於基於 LLM 的全端應用程式的 AI 聊天機器人。 https://github.com/CopilotKit/CopilotKit --- 2. [Storybook](https://github.com/storybookjs/storybook) - UI 開發、測試和文件變得簡單。 --------------------------------------------------------------------------- ![故事書](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/78rfum1ydisn51qhb408.png) Storybook 是一個用於獨立建立 UI 元件和頁面的前端工作坊。它有助於 UI 開發、測試和文件編制。 他們在 GitHub 上有超過 57,000 次提交、81,000 多個 star 和 1300 多個版本。 這是您為專案建立簡單元件的方法。 ``` import type { Meta, StoryObj } from '@storybook/react'; import { YourComponent } from './YourComponent'; //👇 This default export determines where your story goes in the story list const meta: Meta<typeof YourComponent> = { component: YourComponent, }; export default meta; type Story = StoryObj<typeof YourComponent>; export const FirstStory: Story = { args: { //👇 The args you need here will depend on your component }, }; ``` 您可以閱讀[文件](https://storybook.js.org/docs/get-started/setup)。 如今,UI 除錯起來很痛苦,因為它們與業務邏輯、互動狀態和應用程式上下文糾纏在一起。 Storybook 提供了一個獨立的 iframe 來渲染元件,而不會受到應用程式業務邏輯和上下文的干擾。這可以幫助您將開發重點放在元件的每個變體上,甚至是難以觸及的邊緣情況。 https://github.com/storybookjs/storybook --- 3. [Appwrite](https://github.com/appwrite/appwrite) - 您的後端減少麻煩。 --------------------------------------------------------------- ![應用程式寫入](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8x568uz21seyygw6b72z.png) ![帶有 appwrite 的 sdk 列表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cp7k8qnamsluto7eifpl.png) Appwrite 的開源平台可讓您將身份驗證、資料庫、函數和儲存體新增至您的產品中,並建立任何規模的任何應用程式、擁有您的資料並使用您喜歡的編碼語言和工具。 他們有很好的貢獻指南,甚至不厭其煩地詳細解釋架構。 開始使用以下 npm 指令。 ``` npm install appwrite ``` 您可以像這樣建立一個登入元件。 ``` "use client"; import { useState } from "react"; import { account, ID } from "./appwrite"; const LoginPage = () => { const [loggedInUser, setLoggedInUser] = useState(null); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [name, setName] = useState(""); const login = async (email, password) => { const session = await account.createEmailSession(email, password); setLoggedInUser(await account.get()); }; const register = async () => { await account.create(ID.unique(), email, password, name); login(email, password); }; const logout = async () => { await account.deleteSession("current"); setLoggedInUser(null); }; if (loggedInUser) { return ( <div> <p>Logged in as {loggedInUser.name}</p> <button type="button" onClick={logout}> Logout </button> </div> ); } return ( <div> <p>Not logged in</p> <form> <input type="email" placeholder="Email" value={email} onChange={(e) => setEmail(e.target.value)} /> <input type="password" placeholder="Password" value={password} onChange={(e) => setPassword(e.target.value)} /> <input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} /> <button type="button" onClick={() => login(email, password)}> Login </button> <button type="button" onClick={register}> Register </button> </form> </div> ); }; export default LoginPage; ``` 您可以閱讀[文件](https://appwrite.io/docs)。 Appwrite 可以非常輕鬆地建立具有開箱即用的擴充功能的可擴展後端應用程式。 https://github.com/appwrite/appwrite --- 4. [Wasp](https://github.com/wasp-lang/wasp) - 用於 React、node.js 和 prisma 的類似 Rails 的框架。 --------------------------------------------------------------------------------------- ![黃蜂](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fi2mwazueoc3ezjx8a9q.png) 使用 React 和 Node.js 開發全端 Web 應用程式的最快方法。這不是一個想法,而是一種建立瘋狂快速全端應用程式的不同方法。 這是將其整合到元件中的方法。 ``` import getRecipes from "@wasp/queries/getRecipes"; import { useQuery } from "@wasp/queries"; import type { User } from "@wasp/entities"; export function HomePage({ user }: { user: User }) { // Due to full-stack type safety, `recipes` will be of type `Recipe[]` here. const { data: recipes, isLoading } = useQuery(getRecipes); // Calling our query here! if (isLoading) { return <div>Loading...</div>; } return ( <div> <h1>Recipes</h1> <ul> {recipes ? recipes.map((recipe) => ( <li key={recipe.id}> <div>{recipe.title}</div> <div>{recipe.description}</div> </li> )) : 'No recipes defined yet!'} </ul> </div> ); } ``` 您可以閱讀[文件](https://wasp-lang.dev/docs)。 https://github.com/wasp-lang/wasp --- 5. [Novu](https://github.com/novuhq/novu) - 將應用程式內通知新增至您的應用程式! -------------------------------------------------------------- ![再次](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/716b7biilet4auudjlcu.png) Novu 提供開源通知基礎架構和功能齊全的嵌入式通知中心。 這就是如何使用`React`建立 novu 元件以用於應用程式內通知。 ``` import { NovuProvider, PopoverNotificationCenter, NotificationBell, } from "@novu/notification-center"; function App() { return ( <> <NovuProvider subscriberId={process.env.REACT_APP_SUB_ID} applicationIdentifier={process.env.REACT_APP_APP_ID} > <PopoverNotificationCenter> {({ unseenCount }) => <NotificationBell unseenCount={unseenCount} />} </PopoverNotificationCenter> </NovuProvider> </> ); } export default App; ``` 您可以閱讀[文件](https://docs.novu.co/getting-started/introduction)。 https://github.com/novuhq/novu --- 6. [Remotion](https://github.com/remotion-dev/remotion) - 使用 React 以程式設計方式製作影片。 ------------------------------------------------------------------------------- ![遠端](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wmnrxhsc7b9mm5oagflm.png) 使用 React 建立真正的 MP4 影片,使用伺服器端渲染和參數化擴展影片製作。 開始使用以下 npm 指令。 ``` npm init video ``` 它為您提供了一個幀號和一個空白畫布,您可以在其中使用 React 渲染任何您想要的內容。 這是一個範例 React 元件,它將當前幀渲染為文字。 ``` import { AbsoluteFill, useCurrentFrame } from "remotion";   export const MyComposition = () => { const frame = useCurrentFrame();   return ( <AbsoluteFill style={{ justifyContent: "center", alignItems: "center", fontSize: 100, backgroundColor: "white", }} > The current frame is {frame}. </AbsoluteFill> ); }; ``` 您可以閱讀[文件](https://www.remotion.dev/docs/)。 過去兩年,remotion 團隊因製作 GitHub Wrapped 而聞名。 https://github.com/remotion-dev/remotion --- [7.NocoDB](https://github.com/nocodb/nocodb) - Airtable 的替代品。 ------------------------------------------------------------- ![諾科資料庫](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iw3tchfgyzehye5c39xq.png) Airtable 的免費開源替代品是 NocoDB。它可以使用任何 MySQL、PostgreSQL、SQL Server、SQLite 或 MariaDB 資料庫製作智慧型電子表格。 其主要目標是讓強大的計算工具得到更廣泛的使用。 開始使用以下 npx 指令。 ``` npx create-nocodb-app ``` 您可以閱讀[文件](https://docs.nocodb.com/)。 NocoDB 的建立是為了為世界各地的數位企業提供強大的開源和無程式碼資料庫介面。 您可以非常快速地將airtable資料匯入NocoDB。 https://github.com/nocodb/nocodb --- 8.[新穎](https://github.com/steven-tey/novel)- 所見即所得編輯器,具有人工智慧自動完成功能。 ------------------------------------------------------------------- ![小說](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uo34vd9twpxcpbpzgchi.png) 它使用`Next.js` 、 `Vercel AI SDK` 、 `Tiptap`作為文字編輯器。 開始使用以下 npm 指令。 ``` npm i novel ``` 您可以這樣使用它。有多種選項可用於改進您的應用程式。 ``` import { Editor } from "novel"; export default function App() { return <Editor />; } ``` https://github.com/steven-tey/novel --- 9. [Blitz](https://github.com/blitz-js/blitz) - 缺少 NextJS 的全端工具包。 ----------------------------------------------------------------- ![閃電戰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vz6ineg1o7xyv7pwbuqn.png) Blitz 繼承了 Next.js 的不足,為全球應用程式的交付和擴展提供了經過實戰考驗的函式庫和約定。 開始使用以下 npm 指令。 ``` npm install -g blitz ``` 這就是您如何使用 Blitz 建立新頁面。 ``` const NewProjectPage: BlitzPage = () => { const router = useRouter() const [createProjectMutation] = useMutation(createProject) return ( <div> <h1>Create New Project</h1> <ProjectForm submitText="Create Project" schema={CreateProject} onSubmit={async (values) => { // This is equivalent to calling the server function directly const project = await createProjectMutation(values) // Notice the 'Routes' object Blitz provides for routing router.push(Routes.ProjectsPage({ projectId: project.id })) }} /> </div> ); }; NewProjectPage.authenticate = true NewProjectPage.getLayout = (page) => <Layout>{page}</Layout> export default NewProjectPage ``` 您可以閱讀[文件](https://blitzjs.com/docs/get-started)。 它使建築物改善了數倍。 ![閃電戰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cc4mb5wdksjv1ybx71co.png) https://github.com/blitz-js/blitz --- 10. [Supabase](https://github.com/supabase/supabase) - 開源 Firebase 替代品。 ----------------------------------------------------------------------- ![蘇帕貝斯](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ksfygjhrzhmsg9cnvobs.png) 我們大多數人都已經預料到 SUPABASE 會出現在這裡,因為它實在是太棒了。 開始使用以下 npm 指令 (Next.js)。 ``` npx create-next-app -e with-supabase ``` 這是使用 supabase 建立用戶的方法。 ``` import { createClient } from '@supabase/supabase-js' // Initialize const supabaseUrl = 'https://chat-room.supabase.co' const supabaseKey = 'public-anon-key' const supabase = createClient(supabaseUrl, supabaseKey) // Create a new user const { user, error } = await supabase.auth.signUp({ email: '[email protected]', password: 'example-password', }) ``` 您可以閱讀[文件](https://supabase.com/docs)。 您可以使用身份驗證、即時、邊緣功能、儲存等功能建立一個速度極快的應用程式。 Supabase 涵蓋了這一切! 他們還提供了一些入門套件,例如 AI 聊天機器人和 Stripe 訂閱。 https://github.com/supabase/supabase --- [11.Refine](https://github.com/refinedev/refine) - 企業開源重組工具。 ------------------------------------------------------------ ![精煉](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qx0kd6t2jzdtf90k5ke3.png) 建立具有無與倫比的靈活性的管理面板、儀表板和 B2B 應用程式 您可以在一分鐘內使用單一 CLI 命令進行設定。 它具有適用於 15 多個後端服務的連接器,包括 Hasura、Appwrite 等。 開始使用以下 npm 指令。 ``` npm create refine-app@latest ``` 這就是使用 Refine 新增登入資訊的簡單方法。 ``` import { useLogin } from "@refinedev/core"; const { login } = useLogin(); ``` 您可以閱讀[文件](https://refine.dev/docs/)。 https://github.com/refinedev/refine --- 12. [Zenstack](https://github.com/zenstackhq/zenstack) - 資料庫到 API 和 UI 只需幾分鐘。 ----------------------------------------------------------------------------- ![禪斯塔克](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3b6n2ea3jeeva6uujoex.png) TypeScript 工具包,透過強大的存取控制層增強 Prisma ORM,並釋放其全端開發的全部功能。 開始使用以下 npx 指令。 ``` npx zenstack@latest init ``` 這是透過伺服器適配器建立 RESTful API 的方法。 ``` // pages/api/model/[...path].ts import { requestHandler } from '@zenstackhq/next'; import { enhance } from '@zenstackhq/runtime'; import { getSessionUser } from '@lib/auth'; import { prisma } from '@lib/db'; // Mount Prisma-style APIs: "/api/model/post/findMany", "/api/model/post/create", etc. // Can be configured to provide standard RESTful APIs (using JSON:API) instead. export default requestHandler({ getPrisma: (req, res) => enhance(prisma, { user: getSessionUser(req, res) }), }); ``` 您可以閱讀[文件](https://zenstack.dev/docs/welcome)。 https://github.com/zenstackhq/zenstack --- 13. [Buildship](https://github.com/rowyio/buildship) - 低程式碼視覺化後端建構器。 -------------------------------------------------------------------- ![建造船](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rzlrynz5xephv4t9layd.png) 對於您正在使用無程式碼應用程式建構器(FlutterFlow、Webflow、Framer、Adalo、Bubble、BravoStudio...)或前端框架(Next.js、React、Vue...)建立的應用程式,您需要一個後端來支援可擴展的 API、安全工作流程、自動化等。BuildShip 為您提供了一種完全視覺化的方式,可以在易於使用的完全託管體驗中可擴展地建立這些後端任務。 這意味著您不需要在雲端平台上爭論或部署東西、執行 DevOps 等。只需立即建置和交付 🚀 https://github.com/rowyio/buildship --- 14. [Taipy](https://github.com/Avaiga/taipy) - 將資料和人工智慧演算法整合到生產就緒的 Web 應用程式中。 ----------------------------------------------------------------------------- ![打字](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ohv3johuz92lsaux52oq.png) Taipy 是一個開源 Python 庫,用於輕鬆的端到端應用程式開發, 具有假設分析、智慧管道執行、內建調度和部署工具。 開始使用以下命令。 ``` pip install taipy ``` 這是一個典型的Python函數,也是過濾器場景中使用的唯一任務。 ``` def filter_genre(initial_dataset: pd.DataFrame, selected_genre): filtered_dataset = initial_dataset[initial_dataset['genres'].str.contains(selected_genre)] filtered_data = filtered_dataset.nlargest(7, 'Popularity %') return filtered_data ``` 您可以閱讀[文件](https://docs.taipy.io/en/latest/)。 他們還有很多可供您建立的[演示應用程式教學](https://docs.taipy.io/en/latest/knowledge_base/demos/)。 https://github.com/Avaiga/taipy --- 15. [LocalForage](https://github.com/localForage/localForage) - 改進了離線儲存。 ------------------------------------------------------------------------ ![當地飼料](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4hlrka5pybvmgmo2djel.png) LocalForage 是一個 JavaScript 函式庫,它透過使用非同步資料儲存和簡單的、類似 localStorage 的 API 來改善 Web 應用程式的離線體驗。它允許開發人員儲存多種類型的資料而不僅僅是字串。 開始使用以下 npm 指令。 ``` npm install localforage ``` 只需包含 JS 檔案並開始使用 localForage。 ``` <script src="localforage.js"></script> ``` 您可以閱讀[文件](https://localforage.github.io/localForage/#installation)。 https://github.com/localForage/localForage --- 16. [Zod](https://github.com/colinhacks/zod) - 使用靜態類型推斷的 TypeScript-first 模式驗證。 ------------------------------------------------------------------------------- ![佐德](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1s6zvmqr0lv93vsrhofs.png) 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", }); ``` 您可以閱讀[文件](https://zod.dev/)。 它適用於 Node.js 和所有現代瀏覽器 https://github.com/colinhacks/zod --- 17.[多普勒](https://github.com/DopplerHQ)- 管理你的秘密。 ----------------------------------------------- ![多普勒](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gycxnuiiwsvibryrytlc.png) 您可以透過在具有開發、暫存和生產環境的專案中組織機密來消除機密蔓延。 開始使用以下指令 (MacOS)。 ``` $ brew install dopplerhq/cli/doppler $ doppler --version ``` 這是安裝 Doppler CLI[的 GitHub Actions 工作流程](https://github.com/DopplerHQ/cli-action)。 您可以閱讀[文件](https://docs.doppler.com/docs/start)。 ``` name: Example action on: [push] jobs: my-job: runs-on: ubuntu-latest steps: - name: Install CLI uses: dopplerhq/cli-action@v3 - name: Do something with the CLI run: doppler secrets --only-names env: DOPPLER_TOKEN: ${{ secrets.DOPPLER_TOKEN }} ``` https://github.com/DopplerHQ --- 18. [FastAPI](https://github.com/tiangolo/fastapi) - 高效能、易於學習、快速編碼、可用於生產。 ------------------------------------------------------------------------- ![快速API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h2awncoia6255ycl95lk.png) FastAPI 是一個現代、快速(高效能)的 Web 框架,用於基於標準 Python 類型提示使用 Python 3.8+ 建立 API。 開始使用以下命令。 ``` $ pip install fastapi ``` 這是您開始使用 FastAPI 的方式。 ``` from typing import Union from fastapi import FastAPI app = FastAPI() @app.get("/") def read_root(): return {"Hello": "World"} @app.get("/items/{item_id}") def read_item(item_id: int, q: Union[str, None] = None): return {"item_id": item_id, "q": q} ``` 您的編輯器將自動完成屬性並了解它們的類型,這是使用 FastAPI 的最佳功能之一。 您可以閱讀[文件](https://fastapi.tiangolo.com/)。 https://github.com/tiangolo/fastapi --- 19. [Flowise](https://github.com/FlowiseAI/Flowise) - 拖放 UI 來建立您的客製化 LLM 流程。 ---------------------------------------------------------------------------- ![流動](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ct732wv07pvwx0nmavp5.png) Flowise 是一款開源 UI 視覺化工具,用於建立客製化的 LLM 編排流程和 AI 代理程式。 開始使用以下 npm 指令。 ``` npm install -g flowise npx flowise start OR npx flowise start --FLOWISE_USERNAME=user --FLOWISE_PASSWORD=1234 ``` 這就是整合 API 的方式。 ``` import requests url = "/api/v1/prediction/:id" def query(payload): response = requests.post( url, json = payload ) return response.json() output = query({ question: "hello!" )} ``` 您可以閱讀[文件](https://docs.flowiseai.com/)。 https://github.com/FlowiseAI/Flowise --- 20. [Scrapy](https://github.com/scrapy/scrapy) - Python 的快速進階網頁爬行和抓取框架.. ------------------------------------------------------------------------ ![鬥志旺盛](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k1b2y1hzdsphw43b6v7b.png) Scrapy 是一個快速的高級網路爬行和網頁抓取框架,用於爬行網站並從頁面中提取結構化資料。它可用於多種用途,從資料探勘到監控和自動化測試。 開始使用以下命令。 ``` pip install scrapy ``` 建造並執行您的網路蜘蛛。 ``` pip install scrapy cat > myspider.py <<EOF import scrapy class BlogSpider(scrapy.Spider): name = 'blogspider' start_urls = ['https://www.zyte.com/blog/'] def parse(self, response): for title in response.css('.oxy-post-title'): yield {'title': title.css('::text').get()} for next_page in response.css('a.next'): yield response.follow(next_page, self.parse) EOF scrapy runspider myspider.py ``` 您可以閱讀[文件](https://scrapy.org/doc/)。 它擁有大約 50k+ 的星星,因此對於網頁抓取來說具有巨大的可信度。 https://github.com/scrapy/scrapy --- 21. [Tone](https://github.com/Tonejs/Tone.js) - 在瀏覽器中製作互動式音樂。 ------------------------------------------------------------- ![音調.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fokxsoblaohgs4tx75g3.png) 開始使用以下 npm 指令。 ``` npm install tone ``` 這是您開始使用 Tone.js 的方法 ``` // To import Tone.js: import * as Tone from 'tone' //create a synth and connect it to the main output (your speakers) const synth = new Tone.Synth().toDestination(); //play a middle 'C' for the duration of an 8th note synth.triggerAttackRelease("C4", "8n"); ``` 您可以閱讀[文件](https://github.com/Tonejs/Tone.js?tab=readme-ov-file#installation)。 https://github.com/Tonejs/Tone.js --- 22. [Spacetime](https://github.com/spencermountain/spacetime) - 輕量級 javascript 時區庫。 ----------------------------------------------------------------------------------- ![時空](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/abfyfuzt4nw4h7b8usab.png) 您可以計算遠端時區的時間;支持夏令時、閏年和半球。按季度、季節、月份、週來定位時間.. 開始使用以下 npm 指令。 ``` npm install spacetime ``` 您可以這樣使用它。 ``` <script src="https://unpkg.com/spacetime"></script> <script> var d = spacetime('March 1 2012', 'America/New_York') //set the time d = d.time('4:20pm') d = d.goto('America/Los_Angeles') d.time() //'1:20pm' </script> ``` https://github.com/spencermountain/spacetime --- 23. [Mermaid](https://github.com/mermaid-js/mermaid) - 從類似 markdown 的文字產生圖表。 ---------------------------------------------------------------------------- ![美人魚](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ggubn86xv7fznxol6fw7.png) 您可以使用 Markdown with Mermaid 等文字產生流程圖或序列圖等圖表。 這就是建立圖表的方法。 ``` sequenceDiagram Alice->>John: Hello John, how are you? loop Healthcheck John->>John: Fight against hypochondria end Note right of John: Rational thoughts! John-->>Alice: Great! John->>Bob: How about you? Bob-->>John: Jolly good! ``` 它將做出如下圖。 ![圖表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bbuo2ey5q2x3sjwywizg.png) 您可以閱讀[VS Code](https://docs.mermaidchart.com/plugins/visual-studio-code)的[文件](https://mermaid.js.org/intro/getting-started.html)和外掛程式。 請參閱[即時編輯器](https://mermaid.live/edit#pako:eNpVkE1PwzAMhv9KlvM-2AZj62EIxJd24ADXXLzEbaKlcUkdUDX1v5MONomcnNevXz32UWoyKAvZ4mfCoPHRQRWhVuHeO42T7XZHNhTiFb0nMdRjYelbQETRUbpTwRM1uQ2erbaoDyqI_AbnZfjZVZYFVOBCy8J2DWlLwUQHKmAwKrwRo4gnF5Xid-gd2FEAL9hSyp12pMIpNcee2ArxEhH4LG-3D7TPoAPcnhL_4WVxcgHZkfedqIjMSI5ljbEGZ_LyxwFaSbZYo5JFLg3Eg5Iq9NkHiemjC1oWHBOOZWoM8PlQ_8Un45iiLErwbRY9gcH8PUrumuHKlWs5J2oKpasGPUWfZcvctMVsNrSnlWOb9lNN9ax1xkJk-7VZzVaL1RoWS1zdLuFmuTR6P9-sy8X1vDS3V_MFyL7vfwD_bJ1W)中的範例。 https://github.com/mermaid-js/mermaid --- 24.[公共 API](https://github.com/public-apis/public-apis) - 20 多個類別的 1400 多個 API。 ------------------------------------------------------------------------------- ![公共API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sjapk9rwlzdl6bcyqdnl.png) 我們主要使用外部 API 來建立應用程式,在這裡您可以找到所有 API 的清單。網站連結在最後。 它在 GitHub 上擁有大約 279k+ 顆星。 ![公共API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rld5i88smezo1naawz7a.png) 從儲存庫取得網站連結非常困難。所以,我把它貼在這裡。 網址 - [Collective-api.vercel.app/](https://collective-api.vercel.app/) https://github.com/public-apis/public-apis --- 25. [Framer Motion](https://github.com/framer/motion) - 像魔法一樣的動畫。 ----------------------------------------------------------------- ![成幀器運動](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hn4ecqkrhs8f4729bzps.png) 可用的最強大的動畫庫之一。 Framer 使用簡單的聲明性語法意味著您編寫的程式碼更少。更少的程式碼意味著您的程式碼庫更易於閱讀和維護。 您可以建立事件和手勢,並且使用 Framer 的社區很大,這意味著良好的支援。 開始使用以下 npm 指令。 ``` npm install framer-motion ``` 您可以這樣使用它。 ``` import { motion } from "framer-motion" <motion.div whileHover={{ scale: 1.2 }} whileTap={{ scale: 1.1 }} drag="x" dragConstraints={{ left: -100, right: 100 }} /> ``` 您可以閱讀[文件](https://www.framer.com/motion/introduction/)。 https://github.com/framer/motion --- 26.[順便說一句](https://github.com/btw-so/btw)- 在幾分鐘內建立您的個人部落格。 ---------------------------------------------------------- ![順便提一句](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gnne3lrfpolotmxkdz2m.png) 順便說一句,您可以註冊並使用,而無需安裝任何東西。您也可以使用開源版本自行託管。 ![順便提一句](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2rli7hpoccqwpvba29b4.png) 使用順便說一句建立的[範例部落格](https://www.siddg.com/about)。 https://github.com/btw-so/btw --- 27. [Formbricks](https://github.com/formbricks/formbricks) - 開源調查平台。 -------------------------------------------------------------------- ![成型磚](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tp6ggyom33vdifd3m1vt.png) Formbricks 提供免費、開源的測量平台。透過精美的應用程式內、網站、連結和電子郵件調查收集用戶旅程中每個點的回饋。在 Formbricks 之上建置或利用預先建置的資料分析功能。 開始使用以下 npm 指令。 ``` npm install @formbricks/js ``` 這就是您開始使用 formbricks 的方法。 ``` import formbricks from "@formbricks/js"; if (typeof window !== "undefined") { formbricks.init({ environmentId: "claV2as2kKAqF28fJ8", apiHost: "https://app.formbricks.com", }); } ``` 您可以閱讀[文件](https://formbricks.com/docs/getting-started/quickstart-in-app-survey)。 https://github.com/formbricks/formbricks --- 28. [Stripe](https://github.com/stripe) - 支付基礎設施。 ------------------------------------------------- ![條紋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/79yvcgsi4744cmryh15j.png) 數以百萬計的各種規模的公司在線上和親自使用 Stripe 來接受付款、發送付款、自動化財務流程並最終增加收入。 開始使用以下 npm 指令 (React.js)。 ``` npm install @stripe/react-stripe-js @stripe/stripe-js ``` 這就是使用鉤子的方法。 ``` import React, {useState} from 'react'; import ReactDOM from 'react-dom'; import {loadStripe} from '@stripe/stripe-js'; import { PaymentElement, Elements, useStripe, useElements, } from '@stripe/react-stripe-js'; const CheckoutForm = () => { const stripe = useStripe(); const elements = useElements(); const [errorMessage, setErrorMessage] = useState(null); const handleSubmit = async (event) => { event.preventDefault(); if (elements == null) { return; } // Trigger form validation and wallet collection const {error: submitError} = await elements.submit(); if (submitError) { // Show error to your customer setErrorMessage(submitError.message); return; } // Create the PaymentIntent and obtain clientSecret from your server endpoint const res = await fetch('/create-intent', { method: 'POST', }); const {client_secret: clientSecret} = await res.json(); const {error} = await stripe.confirmPayment({ //`Elements` instance that was used to create the Payment Element elements, clientSecret, confirmParams: { return_url: 'https://example.com/order/123/complete', }, }); if (error) { // This point will only be reached if there is an immediate error when // confirming the payment. Show error to your customer (for example, payment // details incomplete) setErrorMessage(error.message); } else { // Your customer will be redirected to your `return_url`. For some payment // methods like iDEAL, your customer will be redirected to an intermediate // site first to authorize the payment, then redirected to the `return_url`. } }; return ( <form onSubmit={handleSubmit}> <PaymentElement /> <button type="submit" disabled={!stripe || !elements}> Pay </button> {/* Show error message to your customers */} {errorMessage && <div>{errorMessage}</div>} </form> ); }; const stripePromise = loadStripe('pk_test_6pRNASCoBOKtIshFeQd4XMUh'); const options = { mode: 'payment', amount: 1099, currency: 'usd', // Fully customizable with appearance API. appearance: { /*...*/ }, }; const App = () => ( <Elements stripe={stripePromise} options={options}> <CheckoutForm /> </Elements> ); ReactDOM.render(<App />, document.body); ``` 您可以閱讀[文件](https://github.com/stripe/react-stripe-js?tab=readme-ov-file#minimal-example)。 您幾乎可以整合任何東西。它有一個巨大的選項清單。 ![整合](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/67f3pb2i8xolt635rp2p.png) https://github.com/stripe --- 29. [Upscayl](https://github.com/upscayl/upscayl) - 開源 AI 影像升級器。 ---------------------------------------------------------------- ![高級](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2c1837rev5jb260ro2sd.png) 適用於 Linux、MacOS 和 Windows 的免費開源 AI Image Upscaler 採用 Linux 優先概念建構。 它可能與全端無關,但它對於升級圖像很有用。 ![高級](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a4qq1wm3wey3vihn9al4.png) 透過最先進的人工智慧,Upscayl 可以幫助您將低解析度影像變成高解析度。清脆又鋒利! https://github.com/upscayl/upscayl --- 30.[重新發送](https://github.com/resend)- 為開發人員提供的電子郵件 API。 ------------------------------------------------------- ![重發](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x3auhh3hbxjmmzehe5v0.png) 您可以使用 React 建立和傳送電子郵件。 2023 年最受炒作的產品之一。 開始使用以下 npm 指令。 ``` npm install @react-email/components -E ``` 這是將其與 next.js 專案整合的方法。 ``` import { EmailTemplate } from '@/components/email-template'; import { Resend } from 'resend'; const resend = new Resend(process.env.RESEND_API_KEY); export async function POST() { const { data, error } = await resend.emails.send({ from: '[email protected]', to: '[email protected]', subject: 'Hello world', react: EmailTemplate({ firstName: 'John' }), }); if (error) { return Response.json({ error }); } return Response.json(data); } ``` 您可以閱讀[文件](https://resend.com/docs/introduction)。 ![重發](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rer9ym187e4i9l11afkg.png) 基本概念是一個簡單、優雅的介面,讓您可以在幾分鐘內開始發送電子郵件。它可以透過適用於您最喜歡的程式語言的 SDK 直接融入您的程式碼中。 https://github.com/resend --- 哇!如此長的專案清單。 我知道您有更多想法,分享它們,讓我們一起建造:D 如今建立全端應用程式並不難,但每個應用程式都可以透過有效地使用優秀的開源專案來解決任何問題來增加這一獨特因素。 例如,您可以建立一些提供通知或建立 UI 流來抓取資料的東西。 我希望其中一些內容對您的開發之旅有用。他們擁有一流的開發人員經驗;你可以依賴他們。 由於您將要建造東西,因此您可以在這裡找到一些[瘋狂的想法](https://github.com/florinpop17/app-ideas)。 祝你有美好的一天!直到下一次。 --- 原文出處:https://dev.to/copilotkit/im-building-a-full-stack-app-here-are-the-libraries-im-going-to-use-51nk

100 多個帶有原始程式碼的 JavaScript 專案

您是否正在尋找**最好的 JavaScript 專案**來透過原始程式碼增加您的 JavaScript 知識? 在這篇文章中,我分享了 100 個最佳 JavaScript 教學。有各種各樣的專案,例如初學者 JavaScript 專案、中級 JavaScript 專案和高級 JavaScript 專案。 因此,無論您對 JavaScript 有什麼樣的了解,這些專案都會對您有所幫助。 🥳🥳 JavaScript 專案 ------------- JavaScript 是用於 Web 開發的最受歡迎的程式語言之一。它用途廣泛、功能強大,可用於建立各種專案,從簡單的腳本到複雜的 Web 應用程式。 如果您希望提高您的 JavaScript 技能或向潛在雇主展示您的能力,那麼**使用原始程式碼開發 JavaScript 專案**是一個很好的方法。 這裡我給了每個專案的源碼連結。因此,您可以自己練習這些**JavaScript 專案**。 😇 ![成為 JS 專家](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u6gnnsmqtf4irq895e0s.jpg) 最佳 JavaScript 專案創意 ------------------ 讓我們來看看前 100 個 JavaScript 專案並討論如何建立它們。 ### 適合初學者的 JavaScript 專案 如果您是一位想要深入編碼世界或尋求擴展技能的初學者,那麼從**簡單的 JavaScript 專案**開始可能是寓教於樂的絕佳方式。這個初學者級 JavaScript 專案一定會對您有幫助。 #### 圖像顏色選擇器 Javascript ![圖像顏色選擇器 Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zswnpz4eqwkbyzlvxsm0.jpg) JavaScript 中的圖像顏色選擇器是一個**簡單的 JavaScript 專案**,可讓使用者直接從圖像中選擇顏色。 它使用戶能夠以互動方式從網頁上顯示的圖像中選取顏色,從而簡化諸如顏色匹配、顏色採樣或從圖像中提取顏色資訊等任務。 [預覽和程式碼](https://codingartistweb.com/2022/11/image-color-picker-javascript/) #### 數字時鐘 JavaScript ![數字時鐘 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u9ychtonhcv3ccallsze.jpg) JavaScript 中的數位時鐘是一個基於 Web 的應用程式或 JavaScript 專案,它以數位格式在網頁上顯示當前時間。 這是一個常見且簡單的專案,展示如何使用 JavaScript 在網路上建立動態和互動式內容。 [預覽和程式碼](https://dev.to/nehasoni__/digital-clock-using-javascript-2648) #### 使用 JavaScript 的秒錶 ![使用 JavaScript 的秒錶](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3qac5fgivbu54ee4ngy7.jpg) 使用 JavaScript 的秒錶是一個基本的 JavaScript 專案,可讓使用者測量經過的時間。它通常由一個用於開始計時的開始按鈕、一個用於暫停計時器的停止按鈕以及一個用於清除已用時間並重新開始的重置按鈕組成。 [預覽和程式碼](https://dev.to/shantanu_jana/create-a-simple-stopwatch-using-javascript-3eoo) #### RGB 顏色滑桿 JavaScript ![RGB 顏色滑桿 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6pvy2tq5yz6owpj1jqgj.jpg) JavaScript 中的 RGB 顏色滑桿是一個**適合初學者的完美 JavaScript 專案**,它允許使用者透過調整顏色的紅色、綠色和藍色 (RGB) 分量的值來選擇顏色。 此互動式元件通常由三個滑桿或輸入欄位(每個顏色通道一個)以及一個預覽區域組成,該區域根據所選 RGB 值顯示結果顏色。 [預覽和程式碼](https://codingartistweb.com/2023/05/rgb-color-slider-javascript/) #### JavaScript 年齡計算器 ![JavaScript 年齡計算器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g8nuylom621dansflni0.jpg) JavaScript 年齡計算器是適合初學者的簡單 JavaScript 專案,它根據出生日期和當前日期計算一個人的年齡。它通常以生日的形式獲取用戶的輸入,然後計算並顯示他們的年齡。 [預覽和程式碼](https://dev.to/code_mystery/javascript-age-calculator-calculate-age-from-date-of-birth-o9b) #### 懸停時影像縮放 ![懸停時影像縮放](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/llrsmmgwkwjo0feoslk5.jpg) JavaScript 中的懸停圖像縮放功能可讓使用者將遊標懸停在圖像上時放大圖像。 此效果可讓使用者更仔細地查看圖像中的細節,從而增強使用者體驗,而無需使用者點擊其他控製或與其他控制項進行互動。 [預覽和程式碼](https://dev.to/shantanu_jana/image-zoom-on-hover-using-javascript-code-demo-328g) #### OTP 生成器 JavaScript ![OTP 生成器 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ad6rb29svfif5b0zg39j.jpg) JavaScript 中的 OTP(一次性密碼)產生器是一種產生唯一程式碼的工具,該程式碼通常由數字或字母數字字元組成,該程式碼一次性使用或在有限時間內有效。 OTP 通常用於 Web 應用程式中的使用者驗證、雙重認證 (2FA) 和帳戶驗證流程。 [預覽和程式碼](https://codingartistweb.com/2023/12/otp-generator/) #### JavaScript 手電筒效果 ![JavaScript 手電筒效果](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4gyd41fpahtqfvc860h9.jpg) JavaScript 手電筒效果模擬手電筒或聚光燈在網頁上產生的照明。它是一種互動式視覺效果,透過將注意力集中在頁面的特定元素或區域來增強使用者體驗。 實現手電筒效果通常涉及在網頁上建立遮罩層,並允許使用者使用滑鼠或觸控輸入來移動手電筒。 [預覽和程式碼](https://groundtutorial.com/flashlight-effect-with-html-css-javascript/) #### 影像手風琴 ![影像手風琴](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ziojqmkvy1lbnzf1u7gx.jpg) JavaScript 中的圖像手風琴是一種使用者介面元素,它以垂直或水平堆疊的形式顯示一組圖像,允許用戶展開和折疊單個圖像以顯示與每個圖像相關的更多細節或資訊。 這種互動創造了一種視覺上吸引人的方式來呈現圖像集合,同時節省網頁空間。 [預覽和程式碼](https://groundtutorial.com/image-accordion-using-html-css-javascript/) #### 拖放元素 ![拖放元素](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iohtqrsk79qw7lva8ngx.jpg) JavaScript 拖放功能可讓使用者透過點擊網頁元素並將其拖曳到頁面上的不同位置來與它們互動。 此功能通常在 Web 應用程式中用於執行諸如重新排序清單、在容器之間移動元素或建立互動式使用者介面等任務。 [預覽和程式碼](https://groundtutorial.com/draggable-element-javascript/) #### 隨機數產生器 ![隨機數產生器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mpezbhvuioe4hpd87yly.jpg) JavaScript 中的隨機數產生器(RNG)是一種產生指定範圍內或具有特定特徵的隨機數的工具。隨機數通常用於遊戲、模擬、密碼學和統計分析等應用。 JavaScript提供了用於生成隨機數的內建函數和方法,可以根據應用程式的要求進行自訂。 [預覽和程式碼](https://foolishdeveloper.com/random-password-generator-with-javascript/) #### 使用 JavaScript 的小費計算器 ![使用 HTML、CSS 的小費計算器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7mcqubvfib3v63y5vhlu.jpg) [預覽和程式碼](https://groundtutorial.com/tip-calculator-html-css-javascript/) #### HTML、CSS、JS 中的雙範圍滑桿 ![HTML、CSS 中的雙範圍滑桿](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w6knk161ja08o9t3bsh3.jpg) [預覽和程式碼](https://groundtutorial.com/double-range-slider-in-html-css-javascript/) #### 使用 JavaScript 的倒數計時器 ![使用 JavaScript 的倒數計時器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wdi6x6fqxrv8q0o4acs3.jpg) [預覽和程式碼](https://dev.to/shantanu_jana/how-to-build-a-countdown-timer-using-javascript-4f4h) #### 使用 JavaScript 的漸層顏色產生器 ![使用 JavaScript 的漸層顏色產生器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pocfjwy56br7v0zg03kn.jpg) [預覽和程式碼](https://dev.to/shantanu_jana/gradient-color-generator-with-javascript-html-5e3p) #### 使用 Javascript 懸停時圖像縮放 ![使用 Javascript 懸停時圖像縮放](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p50dvkjpswitvvoglt26.jpg) [預覽和程式碼](https://dev.to/shantanu_jana/image-zoom-on-hover-using-javascript-code-demo-328g) ### 中階 JavaScript 專案 對於中級 JavaScript 開發人員來說,有許多專案提供了擴展技能、探索新技術和深入研究 Web 開發概念的機會。以下是為中級開發人員量身定制的 JavaScript 專案想法清單: #### 自訂遊標 ![自訂遊標](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3hg920h1fv61et73v6na.jpg) JavaScript 中的自訂遊標是指以自訂設計的圖形或 HTML 元素取代預設遊標外觀(例如箭頭或手形指標)的能力。這使得網頁開發人員能夠建立與網站主題或品牌相符的獨特且具有視覺吸引力的遊標效果。 [預覽和程式碼](https://foolishdeveloper.com/simple-mouse-cursor-effects-using-javascript-free-code/) #### 回文檢查器應用程式 ![回文檢查器應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eioy07s621eqjc1e5fi5.jpg) JavaScript 中的回文檢查器應用程式是一個簡單的 Web 應用程式,允許使用者輸入一串字元並檢查它是否是回文。 回文是單字、片語、數字或其他字元序列,無論空格、標點符號和大小寫,向前和向後讀起來都相同。 [預覽和程式碼](https://groundtutorial.com/how-to-check-palindrome-in-javascript/) #### 滑動圖像拼圖 Javascript ![滑動圖像拼圖 Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t3gn4vl9mvapb5b3cvot.jpg) JavaScript 中的滑動圖像拼圖是一種經典遊戲,其中圖像被分成較小的圖塊,玩家的目標是透過滑動它們來重新排列圖塊以形成原始圖像。遊戲提供了娛樂性和挑戰性的體驗,同時也考驗玩家解決問題的能力和空間推理能力。 [預覽和程式碼](https://groundtutorial.com/image-puzzle-game-javascript/) #### 使用 Javascript 的貨幣轉換器 ![使用 Javascript 的貨幣轉換器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/41ncmzvsq5pj9a6vbjbn.jpg) 使用 JavaScript 的貨幣轉換器是一個 Web 應用程式,允許用戶根據當前匯率將價值從一種貨幣轉換為另一種貨幣。 用戶通常輸入他們想要轉換的金額,選擇來源貨幣,然後選擇目標貨幣。然後,應用程式從 API 檢索最新的匯率並相應地計算換算後的金額。 [預覽和程式碼](https://codingartistweb.com/2023/03/currency-converter-with-javascript/) #### 猜顏色遊戲Javascript ![猜顏色遊戲Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wp4a678c6zsw05ttmd9i.jpg) JavaScript 中的顏色猜測遊戲是一種互動式 Web 應用程式,玩家會看到目標顏色,並且必須猜測該顏色的 RGB 或十六進位程式碼。遊戲通常會提供線索來幫助玩家做出有根據的猜測,例如在正方形中顯示顏色或提供有關顏色成分(紅色、綠色、藍色)或亮度的提示。 [預覽和程式碼](https://groundtutorial.com/color-guessing-game-javascript/) #### 拖放可排序列表 ![拖放可排序列表](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fgyicbi03b7fac9cje89.jpg) JavaScript 中的拖放可排序清單是一個使用者介面元件,可讓使用者透過將清單中的專案拖曳到新位置來重新排序。 此功能通常在 Web 應用程式中用於執行諸如重新排列待辦事項清單中的專案、對圖庫中的圖像進行排序或在文件管理器中組織文件等任務。 [預覽和程式碼](https://codingartistweb.com/2023/02/drag-and-drop-sortable-list-javascript/) #### 觸碰並拖曳影像滑桿 ![觸碰並拖曳影像滑桿](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s4idy4zthbl0v6wv4nf6.jpg) JavaScript 中的觸控和拖曳圖像滑桿是一個使用者介面元件,可讓使用者水平滑動或拖曳圖像以在圖像庫中導航。這種類型的滑桿針對智慧型手機和平板電腦等支援觸控的裝置進行了最佳化,但也可以與桌面瀏覽器上基於滑鼠的互動無縫協作。 [預覽和程式碼](https://groundtutorial.com/touch-image-slider-using-html-css-javascript/) #### 偵測網路速度 JavaScript ![偵測網路速度 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/twmtmhtmia47dzd9mjr5.jpg) 在 JavaScript 中偵測網路速度涉及測量從伺服器下載已知大小的檔案所需的時間。有多種技術可以實現此目的,包括使用 XMLHttpRequest、fetch API 或 HTML5 功能(例如網路資訊 API)。 [預覽和程式碼](https://foolishdeveloper.com/detect-internet-speed-javascript/) #### JavaScript 模因應用程式 ![JavaScript 模因應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j2q1nbc4ckpwemkok3hx.jpg) JavaScript Memes 應用程式是一個 Web 應用程式,允許使用者瀏覽、搜尋和查看 memes。它通常從 API 或資料庫中獲取模因,並將其顯示在用戶友好的介面中,通常具有分頁、排序、過濾和社交共享選項等功能。用戶可以與迷因互動,例如喜歡或分享它們,並且可以上傳自己的迷因。 [預覽和程式碼](https://codingartistweb.com/2022/10/memes-app-html-css-javascript/) #### 多個骰子滾軸 ![多個骰子滾軸](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tmfp7t045awkyniij91a.jpg) JavaScript 中的多個骰子滾輪是一個允許使用者滾動多個不同類型的骰子(例如,d4、d6、d8、d10、d12、d20)並顯示結果的工具。 它通常用於《龍與地下城》等桌上角色扮演遊戲 (RPG) 中,或用於各種遊戲或教育目的。 [預覽和程式碼](https://codingartistweb.com/2023/10/multiple-dice-roller/) #### 密碼強度背景 ![密碼強度背景](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8hkeyw0wr9bc3ajry59f.jpg) JavaScript 中的密碼強度背景是一項功能,當使用者在輸入欄位中鍵入密碼時,可以提供使用者有關密碼強度的視覺回饋。 此回饋通常是透過更改輸入欄位的背景顏色來提供的,以根據預先定義的標準指示密碼是弱、中等還是強。 [預覽和程式碼](https://codingartistweb.com/2023/10/password-strength-background/) #### 自訂滑鼠懸停效果 ![自訂滑鼠懸停效果](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lm53lriqk83p9qbaa8eg.jpg) JavaScript 中的自訂滑鼠懸停效果是一種視覺效果,當使用者將滑鼠懸停在網頁上的元素上時,效果會變更該元素的外觀或行為。 這種效果可以透過使用 CSS 過渡或動畫結合 JavaScript 事件監聽器來偵測滑鼠懸停事件並觸發所需的效果來實現。 [預覽和程式碼](https://codingartistweb.com/2023/12/custom-mouse-hover-effect-with-javascript/) #### 文字相似度檢查器 ![文字相似度檢查器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g4m8phfjm38cc0uug7tf.jpg) JavaScript 中的文字相似度檢查器是一種測量兩段文字或文件之間相似性的工具或應用程式。 文字相似度可以使用各種演算法和技術來計算,例如餘弦相似度、Jaccard 相似度、Levenshtein 距離或 TF-IDF(詞頻-逆文件頻率)。 [預覽和程式碼](https://codingartistweb.com/2023/09/text-similarity-checker/) #### 使用 JavaScript 的拋硬幣遊戲 ![使用 JavaScript 的拋硬幣遊戲](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gtd74ui4i8ds0q6k3b6o.jpg) [預覽和程式碼](https://dev.to/shantanu_jana/coin-toss-game-using-javascript-css-1cf0) #### Javascript 剪刀石頭布遊戲 ![Javascript 剪刀石頭布遊戲](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/if9zccyex7o9n0sfgpt7.jpg) [預覽和程式碼](https://groundtutorial.com/rock-paper-scissor-game-javascript/) #### JavaScript 中的右鍵上下文選單 ![JavaScript 中的右鍵上下文選單](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ope2hkppwntnhnrgskf9.jpg) [預覽和程式碼](https://dev.to/shantanu_jana/custom-right-click-context-menu-in-javascript-4112) ### 高級 JavaScript 專案 高階 JavaScript 專案通常涉及建立複雜的 Web 應用程式或利用複雜框架、程式庫和 API 的軟體解決方案。 這些專案可能需要前端開發、後端開發或全端開發的專業知識。以下是高級 JavaScript 專案的一些範例: #### 帶有儲存的隨機報價產生器 ![帶有儲存的隨機報價產生器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/duvtugkuougrls6ylu6b.jpg) JavaScript 中帶有儲存功能的隨機報價產生器是一個 Web 應用程式,它向用戶顯示隨機報價,並允許他們保存自己喜歡的報價以供以後查看。 該應用程式通常從預先定義清單或外部 API 檢索報價,在網頁上動態顯示它們,並為使用者提供使用 localStorage 儲存和檢索所選報價的選項。 [預覽和程式碼](https://dev.to/nehasoni__/random-quote-generator-using-html-css-and-javascript-3gbp) #### 使用 JavaScript 的螢幕截圖應用程式 ![使用 JavaScript 的螢幕截圖應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8d0edi0hwddzum4k78ux.jpg) 使用 JavaScript 建立螢幕截圖擷取應用程式涉及利用瀏覽器功能來擷取目前網頁或頁面中特定元素的螢幕截圖。 雖然 JavaScript 本身無法直接截取螢幕截圖,但它可以與瀏覽器 API 互動以觸發螢幕截圖擷取功能。 [預覽和程式碼](https://codingartistweb.com/2023/05/screenshot-capture-app-using-javascript/) #### 警報應用程式 JavaScript ![警報應用程式 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bwr8w5254xt70mzcmtvi.jpg) JavaScript 中的鬧鐘應用程式是一個簡單的應用程式,可讓用戶設定鬧鐘並在特定時間接收通知或警報。 它通常涉及用戶互動來設定所需的鬧鐘時間,然後應用程式在背景執行,在達到設定時間時觸發通知。 [預覽和程式碼](https://www.codingnepalweb.com/simple-alarm-clock-html-javascript/) #### 文字轉語音轉換器 ![文字轉語音轉換器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ogf39oucpxjiof9uipjt.jpg) JavaScript 中的文字轉語音 (TTS) 轉換器是一種將書面文字轉換為口語單字的工具或應用程式。它利用瀏覽器 API 或第三方庫將文字合成為語音,並透過裝置的揚聲器或耳機播放。以下是使用 HTML、CSS 和 JavaScript 的文字轉語音轉換器的基本實作: [預覽和程式碼](https://dev.to/shantanu_jana/text-to-speech-converter-with-javascript-30oo) #### QR 碼產生器 JavaScript ![QR 碼產生器 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m0vcmr2mqoy700z80fcc.jpg) JavaScript 中的 QR 程式碼產生器是一種允許使用者在 Web 應用程式中動態建立快速回應 (QR) 程式碼的工具。 QR 碼是二維條碼,可以包含各種類型的訊息,例如 URL、文字、聯絡資訊或 Wi-Fi 憑證。 [預覽和程式碼](https://dev.to/murtuzaalisurti/how-to-make-a-qr-code-generator-using-vanilla-javascript-3cla) #### 測驗應用程式 JavaScript ![測驗應用程式 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aj3aaque8i3myerfuvtn.jpg) JavaScript 中的測驗應用程式是一個互動式 Web 應用程式,它向使用者提出一系列問題並允許他們選擇答案。回答完所有問題後,應用程式會評估答案並提供回饋,例如總分和正確答案。 [預覽和程式碼](https://codingartistweb.com/2022/06/quiz-app-with-javascript/) #### 使用 Javascript 的天氣應用程式 ![使用 Javascript 的天氣應用程式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u3wiz08coy82gig4xe6r.jpg) 使用 JavaScript 的天氣應用程式是一個 Web 應用程式,可為使用者提供特定位置的當前天氣資訊。它通常從天氣 API 檢索天氣資料、處理資料並將其顯示在使用者友好的介面中。 [預覽和程式碼](https://codingartistweb.com/2022/07/weather-app-with-javascript/) #### 自訂視訊播放器 ![自訂視訊播放器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xspo2vpcru8kjvpz6wye.jpg) JavaScript 中的自訂影片播放器是一個 Web JavaScript 專案,它提供用於播放影片內容的自訂使用者介面 (UI)。它通常包括播放、暫停、音量控制、播放速度調整、進度條、全螢幕模式和自訂樣式等功能。 [預覽和程式碼](https://codingartistweb.com/2022/07/custom-video-player-using-javascript/) #### 學生 JavaScript 專案 如果您是學生,那麼這些 JavaScript 專案將對您有很大幫助。 JavaScript 提供了適合不同技能水平的學生(從初學者到高級學習者)的各種專案。 這些專案不僅有助於強化基本概念,也提供 Web 開發的實務經驗。以下是一些**供學生使用的 javascript 專案想法**。 #### 星級評級 JavaScript ![星級評級 JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rm8udkic9kz59e4t528b.jpg) JavaScript 中的星級評級元件是一個學生導向的 JavaScript 專案,可讓使用者透過選擇代表不同滿意度或品質等級的星級來對專案進行評級。通常,它由一組水平排列的可點擊星形圖示組成,其中選定的星形突出顯示以指示使用者的評級。 [預覽和程式碼](https://dev.to/codingnepal/star-rating-system-in-html-css-javascript-97a) #### 五彩紙屑效果 Javascript ![五彩紙屑效果 Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rd6ph3ag1fb4rfnrcgrl.jpg) JavaScript 中的五彩紙屑效果是指一種圖形效果,其中彩色「五彩紙屑」(小紙片或其他材料)在螢幕上散佈或投擲,通常以節日或慶祝的方式進行。 [預覽和程式碼](https://codingartistweb.com/2022/11/confetti-effect-javascript/) #### 刮刮卡Javascript ![刮刮卡Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fsaou1alqoca7ks3swe8.jpg) JavaScript 中的刮刮卡是一個**最好的 js 專案**,它模仿刮掉隱藏區域以顯示下面內容的體驗,類似於彩票或促銷卡。在 Web 開發中,這種效果通常使用 HTML5 畫布元素和 JavaScript 來處理互動來實作。 [預覽和程式碼](https://codingartistweb.com/2022/08/scratch-card-with-javascript/) #### 用 Javascript 進行西蒙遊戲 ![用 Javascript 進行西蒙遊戲](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ob7ng3dcqnvhpbv5z7u2.jpg) 西蒙遊戲是一款經典的記憶技巧電子遊戲。它涉及一個播放一系列音調和燈光的設備,然後玩家必須重複該序列。 在 Simon 遊戲的 JavaScript 實作中,您通常會建立一個使用者介面,其中的按鈕代表每種顏色,遊戲邏輯將涉及產生和顯示一系列顏色供玩家模仿。 [預覽和程式碼](https://dev.to/nanythery/coding-my-first-game-with-javascript-simon-says-60d) #### 自訂音樂播放器 Javascript ![自訂音樂播放器 Javascript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yoexh51at6t9gbau64rb.jpg) 使用 JavaScript 建立自訂音樂播放器涉及建立允許使用者控制音訊播放的使用者介面。[預覽和程式碼](https://dev.to/codingnepal/create-custom-music-player-in-javascript-2367) #### 富文本編輯器 ![富文本編輯器](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7ajobdoysmcm3a8mok0.jpg) 富文本編輯器是一個元件,使用戶能夠使用類似於文字處理器的各種樣式和格式選項來編輯和格式化文字。這些編輯器通常提供粗體、斜體、底線、文字對齊、專案符號、編號清單等功能。 [預覽和程式碼](https://codingartistweb.com/2022/04/rich-text-editor-with-javascript/) > 如果您喜歡這些最佳 JavaScript 專案,那麼我將向此列表加入更多專案。請不要忘記喜歡分享和關注。 使用可用原始碼開始**JavaScript 專案**是增強程式設計技能和擴展知識的絕佳方法。透過剖析現有專案,您可以學習其他人的程式碼,了解不同的設計模式,並發現針對常見挑戰的創新解決方案。😊😊 希望您喜歡這些 JavaScript 專案。您將在我給出的源程式碼連結中獲得逐步說明。希望最佳 JavaScript 專案創意能幫助您增加 JavaScript 知識。 ![專案](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/urerlcgx7v4wkjxqvtmk.jpg) 因此,捲起袖子,深入研究原始碼,開始建立一些令人驚奇的東西! 🥳🥳 --- 原文出處:https://dev.to/shantanu_jana/100-javascript-projects-with-source-code-59lo

關於 GIT 你需要了解的一切

我相信您可以想像版本控製程式碼的重要性,以便我們可以**恢復變更**並**恢復遺失的資料以及其他可能性**。 我打賭你知道有人*(不是我呵呵)*通過使用越來越有創意的名稱建立文件副本來對其文件進行版本控制... ![GIF 模擬具有不同名稱的檔案的複製。範例:文章、文章最終版本等。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sffhjyl41pfnjklivnsv.gif) 在 1972 年之前,隨著**SCCS *(原始碼控制系統)***的發布,這是有史以來第一個**集中式**版本控制軟體之一,這可能是任何人對其程式碼進行版本控制的方式。 但我們在這裡不是在談論 SCCS,我們現在真正感興趣的是**GIT** ,這是一款**分散式**開源版本控制軟體,明年*(07/04/2005)*將慶祝其誕生 20 週年。 目錄 -- - [1.GIT是什麼?](#chapter-1) - [2.GIT如何運作?](#chapter-2) - [3.安裝GIT](#chapter-3) - [4.配置GIT](#chapter-4) - [5. 啟動本機儲存庫](#chapter-5) - [6. 使用 GIT](#chapter-6) - [7. 認識分支](#chapter-7) - [8. 與遠端倉庫同步](#chapter-8) - [9. 結論](#chapter-9) - [10. 參考文獻](#chapter-10) 1.GIT是什麼?<a name="chapter-1"></a> --------------------------------- GIT 是一個開源**分散式**版本控制系統,於 2005 年推出,由 Linus Torvald *(Linux 核心建立者)*開發。 使用GIT,我們可以在本地**控制專案的版本***(在工作資料夾中)*並將所有變更同步到遠端儲存庫*(例如在GitHub上)* 。 2.GIT如何運作?<a name="chapter-2"></a> ---------------------------------- 想像一個**實體**文件櫃,其中有一個包含所有專案文件的資料夾。每當有人需要操作文件時,他們都必須將其拾取,**將其從資料夾中刪除,並在完成後將其返回到資料夾中**。因此,兩個人**不可能**處理同一個文件,完全避免了任何可能的衝突。 **但這不是 Git 的工作原理!** *(感謝上帝)* 這就是**集中式**版本控制系統的工作方式,其中使用者需要**「簽出」**和**「簽入」**文件,即每當有人需要處理特定文件時,他們需要簽出該文件,**刪除從儲存庫中獲取**文件,然後在工作完成後簽入該文件,**並將其返回儲存庫**。 ![GIF 模擬集中式版本控制系統的操作。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/26a9j0m4pcu5prb0kauo.gif) 在像**GIT**這樣的**分散式**系統中,多個人可以存取同一個遠端儲存庫中的檔案。每當有人需要操作文件時,他們只需將其**克隆***(或克隆整個存儲庫)*到本地計算機,然後將修改發送回遠端存儲庫。這使得**多人可以處理同一個專案**,甚至操作**相同的文件**。 ![GIF 模擬分散式版本控制系統的操作。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nb0x0u9kc6m7z2hz7zfj.gif) 這就是允許大型**開源**專案的分佈,來自世界不同地區的人們在同一個專案上工作,管理修改和可能的衝突*(是的,這裡可能會發生合併衝突)* 。 3.安裝GIT<a name="chapter-3"></a> ------------------------------- **GIT**適用於主要作業系統*(Windows、Linux、MacOs...),*安裝過程非常簡單,可以透過**命令列**或透過[git-scm.com](https://git-scm.com/)的**官方安裝程式**完成。 ### 3.1 在 Windows 上 要在 Windows 上安裝 GIT,只需存取官方網站並[下載安裝程式即可](https://git-scm.com/download/win)。然後只需**按照說明進行操作**,一切都會好起來,然後我們就可以在終端機中使用 GIT 命令了。 ### 3.2 在Linux上 對於Linux,我們可以使用以下**命令**安裝**GIT** : ``` sudo apt install git-all ``` 透過這樣做, **GIT**必須準備好在我們的終端中運作。 ### 3.3 在 MacOS 上 對於 Mac,安裝**GIT**最簡單的方法是安裝[Homebrew](https://brew.sh/) ,然後在終端機中執行以下**命令**: ``` brew install git ``` 然後**GIT**必須準備好在我們的終端中運作。 4.配置GIT<a name="chapter-4"></a> ------------------------------- 安裝後,使用以下**命令設定 GIT**很重要: ``` git config --global user.name "[username]" # e.g. John Doe ``` ``` git config --global user. email "[[email protected]]" # e.g. [email protected] ``` > 此外,也可以透過刪除`--global`標籤來為某些本機儲存庫配置特定使用者。 5. 啟動本機儲存庫<a name="chapter-5"></a> ---------------------------------- 配置**GIT**後,我們就可以**啟動本地儲存庫了**。為此,我們可以**從頭開始一個新的儲存庫**或**複製現有的遠端儲存庫**。 ### 5.1 從頭開始(git init) 要啟動新儲存庫,只需導航到所需的儲存庫**根資料夾**並執行以下命令: ``` git init ``` ![Linux 終端機執行「git init」命令並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iw35xe9jwrwzo937to5b.png) 透過這樣做,將在專案資料夾內建立一個`.git`目錄,該目錄將**負責此本機儲存庫的工作資料夾中的版本控制**。 ### 5.2 克隆現有儲存庫(git clone) 克隆現有遠端儲存庫就像從頭開始建立新儲存庫一樣簡單。為此,只需使用`git clone`命令,將要複製**的儲存庫的 URL**作為參數傳遞到要複製儲存庫的資料夾中: 複製現有的遠端儲存庫就像從頭開始建立新的儲存庫一樣簡單。為此,只需使用`git clone`命令,將**遠端儲存庫 URL**克隆到我們要下載儲存庫的資料夾中: ``` git clone [repository-url] ``` ![Linux 終端機執行「git clone」命令並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nlt8rtua4ri7kpnna5el.png) 然後整個存儲庫必須**克隆**到我們的本地機器並**自動連結到相關的遠端存儲庫**。 > 有了複製的儲存庫,我們以後就不再需要使用`git remote`指令了。 6. 使用 GIT<a name="chapter-6"></a> --------------------------------- 在我們的**本機儲存庫**中,我們可以建立專案所需的文件,但它們**不會由 GIT 自動同步**,當有任何變更需要版本控制時,我們需要報告它。 因此,我們可以根據需要**操作**文件,並**在完成所需的變更後**,**將更新的文件傳送到 GIT** 。 為此,重要的是要了解版本控制中有**3 個階段的無限流***(是的,無限)* : ``` MODIFY -> STAGE -> COMMIT ``` - **修改:**版本控制的第一階段,我們在這裡找到與上一個可用版本相比**已更改的檔案**。 - **STAGE:**版本控制的第二階段,這是我們放置**要新增到下次提交的修改檔案**的地方。 - **COMMIT:**版本控制的最後階段,當我們**確認變更**時,將階段中修改的檔案傳送到本機儲存庫。 提交修改後的文件後,我們在本地存儲庫中有一個可用的**新版本**,它可以再次接收更新,再次*“修改”* ,然後放入*“階段”* ,並再次*“提交”* ,確認較新的版本版本等等*(因此,「無限」哈哈)* 。 > 值得注意的是,提交不會覆蓋已修改文件的舊版本,而是包含新版本以及指向最後版本的指針,從而追蹤 GIT 追蹤的每個文件的版本。 ### 6.1 新增和提交(git add 和 git commit) 儘管聽起來很複雜,但執行版本控制流程**非常簡單**。由於所需的修改已完成,我們使用以下命令**新增要在舞台上提交的修改後的檔案**: ``` git add [filename] ``` > `git add -A` -> 將所有修改的檔案立即加入階段。 > > `git add *.[extensão-do-arquivo]` -> 將所有具有指定檔案副檔名的已修改檔案一次新增至暫存區(例如`git add *.html` ) 我們可以隨時使用`git status`指令檢查目前本機儲存庫**狀態**: ![Linux 終端機執行「git status」命令並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e28lg7wym8s0woytgzqz.png) 請注意,當我們**在建立新檔案後**在儲存庫中執行`git status`時,新檔案將顯示為*「Untracked」* 。這意味著該文件是**全新的**,仍然需要加入到任何提交中才能被**GIT追蹤**。 > 可以讓 GIT 忽略儲存庫中的特定檔案或資料夾。為此,我們只需將一個名為`.gitignore`的檔案新增到根資料夾中,並在其中寫入應忽略的檔案或資料夾的名稱。 > > 注意:被忽略的檔案和資料夾將不再出現在 GIT 軌道上,甚至不會顯示為「未追蹤」。要重置跟踪,只需從`.gitignore`文件中刪除所需的名稱即可。 要包含文件,我們可以使用要新增的文件的名稱來執行`git add`命令*(在本例中為「index.html」)* : ![Linux 終端機的螢幕截圖,執行命令“git add”,然後執行“git status”,顯示結果。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pz1hnk9gpnxtv2s8xort.png) 這樣,透過重新執行`git status`我們可以看到新檔案已新增至*「stage」* ,並**最終準備好在下一次提交中發送**,這可以使用以下命令完成: ``` git commit -m "[descriptive-message]" ``` > 提交具有唯一的 ID(雜湊碼)並且是**IMMUTABLE 的**,即一旦確認就無法修改。 > > `git commit -a` -> 執行直接提交,將所有修改的檔案新增至暫存區並提交它們。 **成功提交檔案後**,執行`git status`時,我們注意到**沒有更多修改的檔案需要上傳**,因為所有修改都已在上次**提交**時有效保存在我們的本機儲存庫中。 ![Linux 終端機的螢幕截圖,執行指令“git commit”,然後執行“git status”,顯示結果。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ryqqs4mi46hxtuex199i.png) 此外,還可以使用`git log`指令查看儲存庫的提交日誌來**驗證所做的更改**,該指令顯示所有提交的一些元資料,例如雜湊碼、分支、作者、日期等。 ![Linux 終端機執行命令「git log」並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ljvj9se6srxslsu8vsj7.png) 可以重複整個過程來加入我們專案所需的新文件,修改它們並透過進行新的提交將它們發送到本地儲存庫。 ![GIF 模擬 GIT 分支中的多次提交。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2uez3henix8kchperuw8.gif) > `git log -N` -> 顯示最近 N 次提交的日誌。 > > `git log [branch-A] [branch-B]` -> 顯示「branch-B」中但不在「branch-A」中的提交日誌。 > > `git log --follow [filename]` -> 顯示更改指定檔案的提交日誌,即使它已更改名稱。 > > `git diff` -> 列出與儲存庫中最新可用版本相比所做的變更。 > > `git diff [nome-do-arquivo]` -> 列出對指定檔案相對於儲存庫中最後一個可用版本所做的變更。 ### 6.2 撤銷提交前後的更改 **在提交之前**,對本地存儲庫所做的任何更改都可以撤消或更改,但**一旦提交,就無法更改**。這是因為提交是**不可變的物件**,這意味著不可能編輯或更改提交中的資料。 但是,**可以進行新的提交**來撤銷更改,或更正先前提交中的不正確資訊。無論哪種方式,我們都可以使用以下命令之一: ``` git checkout -- [filename] # Discards changes made to the local file before the commit (irreversible action) ``` ``` git reset --hard HEAD # Discards changes made to a file that is in stage (before the commit) ``` ``` git reset --hard HEAD~1 # Discards the last commit made in the local repository (only the last commit) ``` ``` git commit --amend # Creates a new commit, replacing the last commit made in the local repository ``` ``` git revert [commit-hash] # Creates a new commit, reverting the changes of the specified commit ``` 7. 認識分支<a name="chapter-7"></a> ------------------------------- **分支**只不過是儲存庫的一個**分支**,到目前為止,所有操作都已在分支`master/main'`上執行。 > 預設情況下,儲存庫中建立的第一個分支是`master/main` ,它是儲存庫的主分支。 ### 7.1 為什麼要使用分支? 乍看之下似乎沒什麼,但**分店卻為專案的發展賦予了巨大的力量**。 想像一下,我們正在開發一個 Web 平台,並且想要**測試一項新功能**,但我們的儲存庫已經**託管或與其他人共享**,任何有問題的更改都可能會給他們帶來糟糕的體驗。我們可以做什麼? 如果您一直在考慮**複製並貼上**專案資料夾,建立一個新的**「測試版本」** ,那麼您是對的!嗯,差不多… 透過 GIT,我們可以對分支做類似的事情。由於它們是**分支**,我們可以簡單地**建立一個名為「test」的新分支**,從而在完全**隔離的分支**中擁有我們專案的一個版本,準備好進行翻轉,**而不會危及主分支**。 ![GIF 模擬使用新提交建立新分支。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/szc081nndoi18vklty5r.gif) ### 7.2 建立分支(git分支) 建立**分支**意味著建立可以獨立工作的儲存庫的並行副本,而不會影響`master/main`分支。為此,我們只需執行以下命令: ``` git branch [branch-name] ``` > 在沒有特定分支名稱的情況下執行`git branch`指令必須顯示儲存庫中可用分支的列表,並用「\*」標記目前正在使用的分支。 在執行`git branch test`指令之前, `git branch`指令只會傳回`master`分支。 ![Linux 終端機執行「gitbranch」命令、建立新分支並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vqpdrtvhze9qhr31ewbh.png) 建立新分支後,我們可以執行以下命令在可用分支之間切換: ``` git checkout [branch-name] ``` 執行`git checkout test`指令後,我們可以看到**活動分支已切換**。從那一刻起,**所有提交的資訊都會傳送到儲存庫的`test`分支**,而不會影響分支`master/main` 。 ![Linux 終端機執行「git checkout」命令、切換活動分支並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/egau7y81leig8za36myi.png) > 可以根據需要建立任意數量的分支,並且我們可以使用以下命令與現有分支進行互動: > > `git checkout -b [branch-name]` -> 使用給定名稱建立一個新分支並直接切換到它。 > > `git branch -d [branch-name]` -> 刪除指定分支。 > > `git branch -m [new-name]` -> 將目前分支的名稱變更為給定名稱。 ### 7.3 合併分支(git merge) **當完成不同分支**上的工作,並且我們確定所做的更改不會在專案中引起任何問題時,我們可以將當前分支**合併**到`master/main`分支中,**應用當前分支中的所有更改分支到儲存庫的主分支**。 要**合併**分支,我們需要**切換到將接收更改的分支**並執行以下命令: ``` git merge [branch-name] # Merge the given branch into the active branch ``` 在這裡,由於我們位於分支`test`上,因此我們應該使用`git checkout`命令**切換到分支`master`** ,然後使用我們要合併的分支的名稱*(在本例中為“test”)*執行`git merge`命令。 ![Linux 終端機的螢幕截圖,執行命令“git checkout”,切換到 master 分支,然後“git merge”,顯示結果。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a6tqap1uu5gjipkety6w.png) 透過這樣做,在分支`test`上完成的所有工作*(在本例中為`style.css`檔案的建立)*將合併到分支`master`中。 ![模擬兩個分支之間的合併過程的 GIF。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3hs17m005ogm0qlbedjy.gif) ### 7.4 合併衝突 如果**在同一行上更改了一個或多個檔案**並且合併無法**自動**完成,則使用`git merge`合併不同分支可能會導致一些**衝突**。 ![執行「git merge」命令的 Linux 終端機的螢幕截圖,該命令傳回衝突警告。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9mwedudsff1yf8kpzguc.png) 出現這種情況時,我們可以執行`git status`指令來檢查**哪些檔案**有衝突。 ![出現合併衝突警報後執行「git status」指令的 Linux 終端機的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hcfpmta2yiy1xpyc729u.png) 在繼續合併之前,我們需要**解決衝突**,方法是定義應該進行哪些更改,或檢查更改以使它們相互相容。為此, **GIT 將在衝突文件中插入標記**以協助解決問題。 ![在文字編輯器中開啟的衝突檔案的螢幕截圖,顯示了 GIT 建立的用於幫助解決衝突的標記。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a0e727le3ogmhtuq0g7w.png) 解決衝突後,我們只需要將修改過的檔案放回舞台,提交新的無衝突版本,然後再次執行`git merge`指令,這一定會成功合併,沒有任何問題。 8. 與遠端倉庫同步<a name="chapter-8"></a> ---------------------------------- 我們已經知道可以**將本地存儲庫連接到遠端存儲庫**並遠端同步我們的所有工作,使其**保持最新**。 為此,我們需要執行`git push`命令,該**命令將所有提交從本地存儲庫發送到遠端存儲庫**,但首先我們需要\*\*配置遠端存儲庫。 ### 8.1 配置遠端倉庫 啟動*遠端儲存庫*非常簡單。這裡我們將使用**GitHub**來完成它。 首先,我們需要在 GitHub 帳戶中**啟動一個新的空白儲存庫***(只需選擇一個名稱並點擊「建立儲存庫」)* : ![GitHub 上儲存庫建立頁面的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ug1aw5eq15du36vd1hri.png) 接下來,我們需要透過在本機儲存庫中執行以下命令**來配置遠端儲存庫和本機儲存庫之間的關係**: ``` git remote add origin [remote-repository-url] ``` ![Linux 終端機執行「git Remote」命令並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rhrlfg0f0pgljl5b18vl.png) > `git remote -v` -> 顯示實際連接到本機儲存庫的遠端儲存庫的 URL。 正確**連接**遠端儲存庫後,我們需要使用指令`git branch -m main`**將本機分支`master/main`的名稱變更**為「main」 *(如果您的本機分支已稱為`main` ,請忽略此步驟)* : ![Linux 終端機執行「gitbranch」指令、將「master」分支重新命名為「main」並顯示結果的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f0al7joro01pch0ac124.png) > 保持本機儲存庫的主分支與我們要推送到的遠端儲存庫的主分支同名非常重要。 最後,完成上述步驟後,我們可以使用以下命令首次將本機儲存庫與遠端儲存庫**同步**: ``` git push -u origin main ``` ![執行「git push」命令的 Linux 終端機的螢幕截圖,該命令需要 GitHub 身份驗證。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fvkdyis8y989xron52nc.png) 當我們執行`git push -u origin main`指令時,我們可能需要輸入**GitHub 憑證***(使用者和存取權杖)* 。 > 如果您不知道**GitHub 存取令牌**是什麼,或者您沒有設定存取令牌, [請按一下此處](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-personal-access-token-classic)。 > > 我們也可以透過**使用 GitHub CLI 設定身份驗證**來解決此問題。 [按此處](https://docs.github.com/en/get-started/getting-started-with-git/caching-your-github-credentials-in-git)了解具體方法。 經過**身份驗證**後, `git push`應該會成功執行,將本地儲存庫中的所有提交與遠端儲存庫同步。 ![Linux 終端機的螢幕截圖,顯示 GitHub 驗證後繼續執行「git Push」命令。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vp7q4htszkzrfc6vepcl.png) ![收到帶有新檔案的「git Push」後 GitHub 上的遠端儲存庫的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2rqfhi6s6jh369tseh5y.png) ### 8.2 第一次後的Git推送(git推送) 完成上述所有步驟後,可以單獨使用`git push`指令完成**新同步**,無需任何其他參數,如下所示。 ![Linux 終端機執行「git status」、「git commit」和「git Push」命令、執行新提交並將更新推送到遠端儲存庫的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aoatcspiwosywih07nsm.png) ![收到新更新後 GitHub 上的遠端儲存庫的螢幕截圖。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jskxpghboi62mqw2qcb2.png) > 在這種情況下,使用**GitHub CLI**繞過了執行命令`git push`所需的身份驗證。您可以[點擊此處](https://docs.github.com/en/get-started/getting-started-with-git/caching-your-github-credentials-in-git)了解具體方法。 ### 8.3 更新本地倉庫(git pull) 使用**分散式**遠端儲存庫,可以**遠端**進行更改*(直接在遠端儲存庫中)* ,從而導致我們的本機儲存庫**變得過時**。 考慮到這一點,**更新本機儲存庫**並同步我們在遠端儲存庫中獲得的任何變更非常重要,**以確保本機專案始終具有遠端儲存庫中可用的最新版本**。為此,我們可以執行以下命令: ``` git pull ``` 想像一下,一個**新檔案**`README.md`已**直接在我們的遠端儲存庫中**建立,因此我們的本機儲存庫現已過時。 ![遠端儲存庫的螢幕截圖,其中遠端新增了新的 README.md 檔案。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hccw00vyr7j6lcfm02d2.png) 在本機儲存庫中,我們可以使用上面提到的`git pull`**同步**遠端儲存庫中的變更。 ![Linux 終端機執行「git pull」命令的螢幕截圖,使用遠端儲存庫中的新變更更新本機儲存庫。](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/it9ylx1imd94yey5d0wd.png) > 當我們執行`git pull`指令時回傳的前 7 行是`git fetch`指令的回傳。換句話說,如果我們執行`git pull`命令而不先執行`git fetch`命令,GIT 將同時執行這兩個命令以從遠端存儲庫檢索更新並將其同步到本地存儲庫。 > > `git fetch` -> 從遠端儲存庫取得更新,但不同步本機儲存庫(需要`git pull` )。 9. 結論<a name="chapter-9"></a> ----------------------------- 這一切讓我們確信GIT是程式設計師日常生活中必備的版本控制系統,了解它的主要指令和用途可以成為我們技術資歷的轉捩點。最後,隨著本地和遠端儲存庫的同步和更新,以及我們迄今為止所學到的一切,我們已經準備好繼續推進這個令人敬畏的版本控制系統的實用性。 10. 參考文獻<a name="chapter-10"></a> --------------------------------- - [GIT 的官方文件。](https://git-scm.com/docs/git#_git_commands) - [\[PT-BR\] GIT:入門迷你課程(45 分鐘內學會) - Codigo Fonte TV](https://youtu.be/ts-H3W1uLMM?si=-hKGkUmwgT2lZJwy) --- 原文出處:https://dev.to/reenatoteixeira/everything-that-you-need-to-know-about-git-2440

堅實的原則:它們堅如磐石是有充分理由的!

剛開始接觸**物件導向編程**,對**SOLID**感到有點迷失?不用擔心,在本文中,我將向您解釋它並提供如何在程式碼開發中使用它的範例。 什麼是固體? ------ 在物件導向程式設計中, **SOLID**是五個設計原則的縮寫,旨在增強對軟體的理解、開發和維護。 透過應用這組原則,您應該注意到錯誤的減少、程式碼品質的提高、程式碼組織性更強、耦合性降低、重構增強以及程式碼重用的鼓勵。讓我們來看看他們。 1. S-單一職責原則 ----------- ![建議零售價](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v564d0p0s36fwo6imofo.png) > SRP - 單一職責原則 這確實很簡單,但非常重要:**一個類別應該有一個且只有一個改變的理由。** 不再建立具有多種功能和職責的類,是嗎?您可能遇到甚至建立了一個可以完成所有操作的類,即所謂的*God Class* 。目前看起來似乎沒問題,但是當您需要更改該類別的邏輯時,肯定會出現問題。 > 上帝類別:在OOP中,這是一個`do`或`knows`太多事情的類別。 ``` class ProfileManager { authenticateUser(username: string, password: string): boolean { // Authenticate logic } showUserProfile(username: string): UserProfile { // Show user profile logic } updateUserProfile(username: string): UserProfile { // Update user profile logic } setUserPermissions(username: string): void { // Set permission logic } } ``` 此**ProfileManager**類別執行**四個**不同的任務,違反了 SRP 原則。它正在驗證和更新資料、進行演示,最重要的是,它正在設定權限,所有這些都是同時進行的。 ### 這可能導致的問題 - `Lack of cohesion -`一個類別不應該承擔不屬於它自己的責任; - `Too much information in one place -`你的類別最終會產生許多依賴性並且難以進行更改; - `Challenges in implementing automated tests -`很難模擬這樣的類別。 現在,將**SRP**應用到`ProfileManager`類別中,讓我們來看看這個原則可以帶來的改進: ``` class AuthenticationManager { authenticateUser(username: string, password: string): boolean { // Authenticate logic } } class UserProfileManager { showUserProfile(username: string): UserProfile { // Show user profile logic } updateUserProfile(username: string): UserProfile { // Update user profile logic } } class PermissionManager { setUserPermissions(username: string): void { // Set permission logic } } ``` 您可能想知道, `can I apply this only to classes?`答案是:**完全不是**。您也可以(並且應該)將其應用於方法和函數。 ``` // ❌ function processTasks(taskList: Task[]): void { taskList.forEach((task) => { // Processing logic involving multiple responsibilities updateTaskStatus(task); displayTaskDetails(task); validateTaskCompletion(task); verifyTaskExistence(task); }); } // ✅ function updateTaskStatus(task: Task): Task { // Logic for updating task status return { ...task, completed: true }; } function displayTaskDetails(task: Task): void { // Logic for displaying task details console.log(`Task ID: ${task.id}, Description: ${task.description}`); } function validateTaskCompletion(task: Task): boolean { // Logic for validating task completion return task.completed; } function verifyTaskExistence(task: Task): boolean { // Logic for verifying task existence return tasks.some((t) => t.id === task.id); } ``` 美麗、優雅、有組織的程式碼。這個原則是其他原則的基礎;透過應用它,您應該建立高品質、可讀且可維護的程式碼。 2. O——開閉原則 ---------- ![OCP](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/epfur4p9r55iwbk9i4yy.png) > OCP-開閉原則 **物件或實體應該對擴充開放,但對修改關閉。**如果您需要加入功能,最好擴展而不是修改原始程式碼。 想像一下,您需要一個類別來計算某些多邊形的面積。 ``` class Circle { radius: number; constructor(radius: number) { this.radius = radius; } area(): number { return Math.PI * this.radius ** 2; } } class Square { sideLength: number; constructor(sideLength: number) { this.sideLength = sideLength; } calculateArea(): number { return this.sideLength ** 2; } } class areaCalculator { totalArea(shapes: Shape[]): number { let total = 0; shapes.forEach((shape) => { if (shape instanceof Square) { total += (shape as any).calculateArea(); } else { total += shape.area(); } }); return total; } } ``` `areaCalculator`類別的任務是計算不同多邊形的面積,每個多邊形都有自己的面積邏輯。如果您,'lil dev,需要加入新形狀,例如三角形或矩形,您會發現自己**需要**更改此類來進行更改,對吧?這就是你遇到問題的地方,違反了`Open-Closed Principle` 。 我想到了什麼解決方案?可能會在類別中加入另一個方法並完成,問題解決了🤩。不完全是,年輕學徒😓,這就是問題所在! **修改現有類別以新增行為會帶來嚴重的風險,可能會將錯誤引入到已執行的內容中。** > 請記住:OCP 堅持認為類別應該對修改關閉,對擴展開放。 看看重構程式碼帶來的美妙之處: ``` interface Shape { area(): number; } class Circle implements Shape { radius: number; constructor(radius: number) { this.radius = radius; } area(): number { return Math.PI * this.radius ** 2; } } class Square implements Shape { sideLength: number; constructor(sideLength: number) { this.sideLength = sideLength; } area(): number { return this.sideLength ** 2; } } class AreaCalculator { totalArea(shapes: Shape[]): number { let total = 0; shapes.forEach((shape) => { total += shape.area(); }); return total; } } ``` 查看`AreaCalculator`類別:它不再需要知道要呼叫哪些方法來註冊該類別。它可以透過呼叫介面強加的契約來正確地呼叫區域方法,這是它唯一需要的。 > 只要它們實作了 Shape 接口,一切就可以正常運作。 &lt;br/&gt; > 分離介面背後的可擴展行為並反轉依賴關係。 &gt; > [鮑伯叔叔](https://en.wikipedia.org/wiki/Robert_C._Martin) - `Open for extension:`您可以為類別新增功能或行為,而無需變更其原始程式碼。 - `Closed for modification:`如果您的類別已經具有可以正常工作的功能或行為,請不要更改其原始程式碼以加入新內容。 3. L——里氏代換原理 ------------ ![LSP](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/62uow23fsa5zk2wz5fz5.png) > LSP - 里氏替換原理 里氏替換原則指出**衍生類別必須可替換其基底類別。** 這個原則由 Barbara Liskov 在 1987 年提出,閱讀她的解釋可能會有點複雜。不過,不用擔心,我將提供另一個解釋和範例來幫助您理解。 > 如果對於 S 類型的每個物件 o1 都有一個 T 類型的物件 o2,使得對於所有用 T 定義的程式 P,當 o1 取代 o2 時 P 的行為保持不變,則 S 是 T 的子類型。 &gt; > 芭芭拉‧利斯科夫,1987 你做對了?不,可能不是。是的,我第一次讀時不明白(接下來的一百遍也不明白),但等等,還有另一種解釋: > 如果 S 是 T 的子類型,則程式中類型 T 的物件可以用類型 S 的物件替換,而不改變該程式的屬性。 &gt; > [維基百科](https://en.wikipedia.org/wiki/Liskov_substitution_principle) 如果您更喜歡視覺學習者,請不要擔心,這裡有一個例子: ``` class Person { speakName() { return "I am a person!"; } } class Child extends Person { speakName() { return "I am a child!"; } } const person = new Person(); const child = new Child(); function printName(message: string) { console.log(message); } printName(person.speakName()); // I am a person! printName(child.speakName()); // I am a child! ``` 父類別和衍生類別作為參數傳遞,程式碼繼續按預期工作。魔法?是的,這就是我們的朋友倒鉤的魔力。 ### 違規行為範例: - 重寫/實作一個不執行任何操作的方法; - 從基類傳回不同類型的值。 - 拋出意外的異常; 4. I——介面隔離原則 ------------ ![網際網路服務供應商](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qbdmugukrcacuqthho5x.png) > ISP-介面隔離原則 這句話說**不應該強迫一個類別實作它不使用的介面和方法。**建立更具體的介面比建立大而通用的介面更好。 在下面的範例中,建立一個**Book**介面來抽象化書籍行為,然後類別實作該介面: ``` interface Book { read(): void; download(): void; } class OnlineBook implements Book { read(): void { // does something } download(): void { // does something } } class PhysicalBook implements Book { read(): void { // does something } download(): void { // This implementation doesn't make sense for a book // it violates the Interface Segregation Principle } } ``` 通用`Book`介面迫使`PhysicalBook`類別做出毫無意義的行為(*或者我們在 Matrix 中下載實體書籍?* )並且違反了**ISP**和**LSP**原則。 使用**ISP**解決此問題: ``` interface Readable { read(): void; } interface Downloadable { download(): void; } class OnlineBook implements Readable, Downloadable { read(): void { // does something } download(): void { // does something } } class PhysicalBook implements Readable { read(): void { // does something } } ``` 現在好多了。我們從`Book`介面中刪除了`download()`方法,並將其加入到派生介面`Downloadable`中。這樣,行為就可以在我們的上下文中正確隔離,並且我們仍然尊重**介面隔離原則**。 5.D-依賴倒置原則 ---------- ![沾](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/42aomc36xq804pyldlis.png) > DIP - 依賴倒置原理 這個是這樣的:**依賴抽象而不是實現。** > 高層模組不應該依賴低層模組。兩者都應該依賴抽象。 &gt; > 抽像不應該依賴細節。細節應該取決於抽象。 &gt; > 鮑伯叔叔 現在我將展示一個簡單的程式碼來說明 DIP。在此範例中,有一個從資料庫取得使用者的服務。首先,讓我們建立一個與資料庫連接的具體類別: ``` // Low-level module class MySQLDatabase { getUserData(id: number): string { // Logic to fetch user data from MySQL database } } ``` 現在,讓我們建立一個取決於具體實作的服務類別: ``` // High-level module class UserService { private database: MySQLDatabase; constructor() { this.database = new MySQLDatabase(); } getUser(id: number): string { return this.database.getUserData(id); } } ``` 在上面的範例中, `UserService`直接依賴`MySQLDatabase`的具體實作。這違反了**DIP** ,因為**高級**類別 UserService 直接依賴**低階**類別。 如果我們想要切換到不同的資料庫系統(例如PostgreSQL),我們需要修改UserService類,這`AWFUL`了! 讓我們使用**DIP**修復此程式碼。高級類別`UserService`不應依賴特定實現,而應依賴抽象。讓我們建立一個`Database`介面作為抽象: ``` // Abstract interface (abstraction) for the low-level module interface Database { getUserData(id: number): string; } ``` 現在, `MySQLDatabase`和`PostgreSQLDatabase`的具體實作應該要實作這個介面: ``` class MySQLDatabase implements Database { getUserData(id: number): string { // Logic to fetch user data from MySQL database } } // Another low-level module implementing the Database interface class PostgreSQLDatabase implements Database { getUserData(id: number): string { // Logic to fetch user data from PostgreSQL database } } ``` 最後,UserService 類別可以依賴`Database`抽象: ``` class UserService { private database: Database; constructor(database: Database) { this.database = database; } getUser(id: number): string { return this.database.getUserData(id); } } ``` 這樣, `UserService`類別依賴`Database`抽象,而不是具體實現,滿足**依賴倒置原則**。 結論 -- 透過採用這些原則,開發人員可以建立更能適應變化的系統,使維護變得更容易,並隨著時間的推移提高程式碼品質。 本文的全部內容源自各種其他文章、我的個人筆記以及我**在深入研究物件導向程式設計 (OOP) 領域**時遇到的數十個線上影片。範例中使用的程式碼片段是基於我對這些原則的解釋和理解而建立的。我真的希望,我的小學徒,我能為促進你的理解和學習進步做出貢獻。 衷心希望您喜歡這篇文章,別忘了關注! 註:圖片取自[本文](https://medium.com/backticks-tildes/the-s-o-l-i-d-principles-in-pictures-b34ce2f1e898) --- 原文出處:https://dev.to/lukeskw/solid-principles-theyre-rock-solid-for-good-reason-31hn

🪄與您的簡歷製作者聊天 - 使用 Next.js、OpenAI 和 CopilotKit 📑✨

#TL;博士 在本文中,您將了解如何使用 Nextjs、CopilotKit 和 OpenAI 建立人工智慧驅動的簡歷產生器應用程式。 我們將涵蓋: - 利用 ChatGPT 撰寫履歷和求職信 📑 - 透過與履歷聊天逐漸完善你的履歷💬 - 將您的履歷和求職信匯出為 PDF 🖨️ ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jxzcx6jqet2anmr2pu6c.gif) --- ## CopilotKit:建構深度整合的應用內人工智慧聊天機器人 💬 只是簡單介紹一下我們的背景。 CopilotKit 是[開源 AI 副駕駛平台。](https://github.com/CopilotKit/CopilotKit) 我們可以輕鬆地將強大的 AI 聊天機器人整合到您的 React 應用程式中。完全可定制和深度集成。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6wf9zcyvtu9q293uej2n.gif) {% cta https://github.com/CopilotKit/CopilotKit %} Star CopilotKit ⭐️ {% endcta %} 現在回到文章。 --- ## **先決條件** 要開始學習本教程,您需要在電腦上安裝以下軟體: - 文字編輯器(例如 Visual Studio Code) - 節點.js - 套件管理器 ## **使用 NextJS 建立簡歷應用程式前端** **步驟 1:** 開啟命令提示字元並執行下列命令。 ``` npx create-next-app@latest ``` --- **第 2 步:** 系統將提示您選擇一些選項,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mvk0mgct4ypra7ao9u18.png) **步驟 3:** 使用您選擇的文字編輯器開啟新建立的 Nextjs 專案。然後,在命令列上執行以下命令,以使用 Tailwind CSS 安裝帶有 NextJS 的 Preline UI。依照[本指南](https://preline.co/docs/frameworks-nextjs.html)完成 Preline 設定。 ``` npm install preline ``` --- **步驟4:** 在resume/app/page.tsx檔案中,新增以下程式碼內容。 ``` export default function Home() { return ( <> <header className="flex flex-wrap sm:justify-start sm:flex-nowrap z-50 w-full bg-slate-900 bg-gradient-to-b from-violet-600/[.15] via-transparent text-sm py-3 sm:py-0 dark:bg-gray-800 dark:border-gray-700"> <nav className="relative max-w-7xl w-full mx-auto px-4 sm:flex sm:items-center sm:justify-between sm:px-6 lg:px-8 " aria-label="Global"> <div className="flex items-center justify-between"> <a className="flex-none text-xl text-gray-200 font-semibold dark:text-white py-8" href="#" aria-label="Brand"> ResumeBuilder </a> </div> </nav> </header> {/* <!-- Hero --> */} <div className="bg-slate-900 h-screen"> <div className="bg-gradient-to-b from-violet-600/[.15] via-transparent"> <div className="max-w-[85rem] mx-auto px-4 sm:px-6 lg:px-8 py-24 space-y-8"> {/* <!-- Title --> */} <div className="max-w-3xl text-center mx-auto pt-10"> <h1 className="block font-medium text-gray-200 text-4xl sm:text-5xl md:text-6xl lg:text-7xl"> Craft A Compelling Resume With AI Resume Builder </h1> </div> {/* <!-- End Title --> */} <div className="max-w-3xl text-center mx-auto"> <p className="text-lg text-gray-400"> ResumeBuilder helps you create a resume that effectively highlights your skills and experience. </p> </div> {/* <!-- Buttons --> */} <div className="text-center"> <a className="inline-flex justify-center items-center gap-x-3 text-center bg-gradient-to-tl from-blue-600 to-violet-600 shadow-lg shadow-transparent hover:shadow-blue-700/50 border border-transparent text-white text-sm font-medium rounded-full focus:outline-none focus:ring-2 focus:ring-blue-600 focus:ring-offset-2 focus:ring-offset-white py-3 px-6 dark:focus:ring-offset-gray-800" href="#"> Get started <svg className="flex-shrink-0 w-4 h-4" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <path d="m9 18 6-6-6-6" /> </svg> </a> </div> {/* <!-- End Buttons --> */} </div> </div> </div> {/* <!-- End Hero --> */} </> ); } ``` **步驟 5:** 在命令列上執行命令 *npm run dev*。導航至 http://localhost:3000/,您應該會看到新建立的 NextJS 專案。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/56ymnb9iir7z14bx4ofm.png) --- ## 使用 GitHub GraphQL 從 GitHub 取得履歷資料 **步驟 1:** 使用下列命令安裝 Axios HTTP 用戶端。 ``` npm i axios ``` **步驟 2:** 在應用程式資料夾中,建立一個名為 API 的資料夾。然後,在 API 資料夾中建立一個名為 GitHub 的資料夾。在GitHub資料夾中建立一個名為route.ts的檔案並加入以下程式碼。 ``` import { NextResponse } from "next/server"; import axios from "axios"; // Environment variables for GitHub API token and user details const GITHUB_TOKEN = "Your GitHub personal access token"; const GITHUB_USERNAME = "Your GitHub account username"; // Axios instance for GitHub GraphQL API const githubApi = axios.create({ baseURL: "https://api.github.com/graphql", headers: { Authorization: `bearer ${GITHUB_TOKEN}`, "Content-Type": "application/json", }, }); // GraphQL query to fetch user and repository data const getUserAndReposQuery = ` query { user(login: "${GITHUB_USERNAME}") { name email company bio repositories(first: 3, orderBy: {field: CREATED_AT, direction: DESC}) { edges { node { name url description createdAt ... on Repository { primaryLanguage{ name } stargazers { totalCount } } } } } } } `; // API route to handle resume data fetching export async function GET(request: any) { try { // Fetch data from GitHub const response = await githubApi.post("", { query: getUserAndReposQuery }); const userData = response.data.data.user; // Format resume data const resumeData = { name: userData.name, email: userData.email, company: userData.company, bio: userData.bio, repositories: userData.repositories.edges.map((repo: any) => ({ name: repo.node.name, url: repo.node.url, created: repo.node.createdAt, description: repo.node.description, language: repo.node.primaryLanguage.name, stars: repo.node.stargazers.totalCount, })), }; // Return formatted resume data return NextResponse.json(resumeData); } catch (error) { console.error("Error fetching data from GitHub:", error); return NextResponse.json({ message: "Internal Server Error" }); } } ``` **步驟 3:** 在應用程式資料夾中,建立一個名為 Components 的資料夾。然後,在元件資料夾中建立一個名為 githubdata.tsx 的檔案並新增以下程式碼。 ``` "use client"; import React, { useEffect, useState } from "react"; import axios from "axios"; // Resume data interface interface ResumeData { name: string; email: string; company: string; bio: string; repositories: { name: string; url: string; created: string; description: string; language: string; stars: number; }[]; } export const useGithubData = () => { const [resumeData, setResumeData] = useState<ResumeData | null>(null); // Fetch resume data from API useEffect(() => { axios .get("/api/github") .then((response) => { setResumeData(response.data); }) }, []); return { resumeData, }; } ``` --- ## 建立求職信和履歷功能 **步驟 1:** 透過在命令列上執行以下命令來安裝 CopilotKit 前端軟體包。 ``` npm i @copilotkit/react-core @copilotkit/react-ui @copilotkit/react-textarea ``` **步驟2:** 在元件資料夾中建立一個名為resume.tsx 的檔案。然後在檔案頂端匯入 useMakeCopilotReadable、useMakeCopilotActionable 和 useGithubData 自訂掛鉤,如下所示。 ``` import React, { useState } from "react"; import { useGithubData } from "./githubdata"; import { useMakeCopilotReadable, useMakeCopilotActionable, } from "@copilotkit/react-core"; ``` **第 3 步:** 建立一個名為 CoverLetterAndResume 的元件。在元件內部,使用 useGithubData 掛鉤檢索從 GitHub 取得的資料。然後,宣告一個名為 createCoverLetterAndResume 的狀態變數和一個用於更新它的名為 setCreateCoverLetterAndResume 的函數。使用包含 letter 和 resume 兩個屬性的物件初始化 useState,如下所示。 ``` export const CoverLetterAndResume = () => { const {resumeData } = useGithubData(); const [createCoverLetterAndResume, setCreateCoverLetterAndResume] = useState({ letter: "", resume: "" }); } ``` **步驟 4:** 使用 useMakeCopilotReadable 掛鉤將從 GitHub 取得的資料新增為應用程式內聊天機器人的上下文。 ``` useMakeCopilotReadable(JSON.stringify(resumeData)); ``` **步驟 5:** 使用 useMakeCopilotActionable 掛鉤設定一個名為 createCoverLetterAndResume 的操作,其中包含描述和實作函數,該函數使用提供的求職信和簡歷更新 createCoverLetterAndResume 狀態,如下所示。 ``` useMakeCopilotActionable( { name: "createCoverLetterAndResume", description: "Create a cover letter and resume for a software developer job application.", argumentAnnotations: [ { name: "coverLetterMarkdown", type: "string", description: "Markdown text for a cover letter to introduce yourself and briefly summarize your professional background as a software developer.", required: true, }, { name: "resumeMarkdown", type: "string", description: "Markdown text for a resume that displays your professional background and relevant skills.", required: true, }, ], implementation: async (coverLetterMarkdown, resumeMarkdown) => { setCreateCoverLetterAndResume((prevState) => ({ ...prevState, letter: coverLetterMarkdown, resume: resumeMarkdown, })); }, }, [] ); ``` **步驟 6:** 在 CoverLetterAndResume 元件外部,建立一個名為 CoverLetterResume 的元件,用於在 Web 應用程式 UI 上顯示求職信和履歷。 ``` type CoverLetterResumeProps = { letter: string; resume: string; }; const CoverLetterResume = ({ letter, resume }: CoverLetterResumeProps) => { return ( <div className="px-4 sm:px-6 lg:px-8 bg-slate-50 py-4"> <div className="sm:flex sm:items-center"> <div className="sm:flex-auto"> <h1 className="text-3xl font-semibold leading-6 text-gray-900"> ResumeBuilder </h1> </div> </div> {/* Cover Letter Start */} <div className="mt-8 flow-root bg-slate-200"> <div className="-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8"> <div className="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8"> <div> <h2 className="text-lg font-semibold leading-6 text-gray-900 mb-4 p-2"> Cover Letter </h2> <div className="min-w-full divide-y divide-gray-300 p-2"> {/* <Thead /> */} <div className="divide-y divide-gray-200 bg-white p-2"> <ReactMarkdown>{letter}</ReactMarkdown> </div> </div> </div> </div> </div> </div> {/* Cover Letter End */} {/* Cover Letter Preview Start */} <div className="mt-8 flow-root bg-slate-200"> <div className="-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8"> <div className="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8"> <div> <h2 className="text-lg font-semibold leading-6 text-gray-900 mb-4 p-2"> Cover Letter Preview </h2> <div className="min-w-full divide-y divide-gray-300"> {/* <Thead /> */} <div className="divide-y divide-gray-200 bg-white"> <textarea className="p-2" id="coverLetter" value={letter} rows={20} cols={113} /> </div> </div> </div> </div> </div> </div> {/* Cover Letter Preview End */} {/* Resume Start */} <div className="mt-8 flow-root bg-slate-200"> <div className="-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8"> <div className="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8"> <h2 className="text-lg font-semibold leading-6 text-gray-900 mb-4 p-2"> Resume </h2> <div className="min-w-full divide-y divide-gray-300"> {/* <Thead /> */} <div className="divide-y divide-gray-200 bg-white"> <ReactMarkdown>{resume}</ReactMarkdown> </div> </div> </div> </div> </div> {/* Resume End */} {/* Cover Letter Preview Start */} <div className="mt-8 flow-root bg-slate-200"> <div className="-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8"> <div className="inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8"> <div> <h2 className="text-lg font-semibold leading-6 text-gray-900 mb-4 p-2"> Cover Letter Preview </h2> <div className="min-w-full divide-y divide-gray-300"> {/* <Thead /> */} <div className="divide-y divide-gray-200 bg-white"> {/* {letter} */} {/* <ReactMarkdown>{letter}</ReactMarkdown> */} <textarea className="p-2" id="resume" value={resume} rows={20} cols={113} /> </div> </div> </div> </div> </div> </div> {/* Cover Letter Preview End */} </div> ); }; ``` **第7步:**然後返回CoverLetterAndResume元件內的CoverLetterResume元件,如下圖所示。 ``` return <CoverLetterResume {...createCoverLetterAndResume}/>; ``` **第8步:** 在應用程式資料夾中建立一個名為resumeandcoverletter的資料夾。然後,建立一個名為 page.tsx 的檔案並新增以下程式碼。 ``` "use client"; import { CopilotProvider } from "@copilotkit/react-core"; import { CopilotSidebarUIProvider } from "@copilotkit/react-ui"; import "@copilotkit/react-textarea/styles.css"; // also import this if you want to use the CopilotTextarea component import "@copilotkit/react-ui/styles.css"; // also import this if you want to use the chatbot component import React, { useEffect, useState } from "react"; import { CoverLetterAndResume } from "../components/resume"; function buildResume () { return ( <CopilotProvider chatApiEndpoint="./../api/copilotkit/chat"> <CopilotSidebarUIProvider> <CoverLetterAndResume /> </CopilotSidebarUIProvider> </CopilotProvider> ); } export default buildResume; ``` **步驟 9:** 使用下列指令安裝 openai 軟體套件。 ``` npm i openai ``` **步驟 10:** 在應用程式資料夾中,建立一個名為 API 的資料夾。然後,在 API 資料夾中建立一個名為 copilotkit 的資料夾。在 copilotkit 資料夾中,建立一個名為 chat 的資料夾。然後,在聊天資料夾中建立一個名為route.ts的檔案並新增以下程式碼。 ``` import OpenAI from "openai"; const openai = new OpenAI({ apiKey: "Your ChatGPT API key", }); export const runtime = "edge"; export async function POST(req: Request): Promise<Response> { try { const forwardedProps = await req.json(); const stream = openai.beta.chat.completions .stream({ model: "gpt-4-1106-preview", ...forwardedProps, stream: true, }) .toReadableStream(); return new Response(stream); } catch (error: any) { return new Response("", { status: 500, statusText: error.error.message }); } } ``` **步驟 11:** 在應用程式資料夾中的 page.tsx 檔案中,在「開始」按鈕中新增一個連結,用於導航到簡歷和求職信頁面,如下所示。 ``` <div className="text-center"> <Link className="inline-flex justify-center items-center gap-x-3 text-center bg-gradient-to-tl from-blue-600 to-violet-600 shadow-lg shadow-transparent hover:shadow-blue-700/50 border border-transparent text-white text-sm font-medium rounded-full focus:outline-none focus:ring-2 focus:ring-blue-600 focus:ring-offset-2 focus:ring-offset-white py-3 px-6 dark:focus:ring-offset-gray-800" href="/resumeandcoverletter"> Get started <svg className="flex-shrink-0 w-4 h-4" xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <path d="m9 18 6-6-6-6" /> </svg> </Link> </div> ``` **第12步:**導航至http://localhost:3000/,點擊「開始」按鈕,您將被重新導向到與聊天機器人整合的履歷和求職信頁面,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yqfjykc75pherkjxut4p.png) **第 13 步:** 向右側的聊天機器人發出諸如“建立求職信和簡歷”之類的提示。聊天機器人將開始產生回應,完成後,它將在頁面左側顯示產生的求職信和履歷,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t7muhhi4a85ol0ddyi1l.png) --- ## 建立更新求職信功能 **第 1 步:** 宣告一個名為 updateLetter 的變數,用於保存先前產生的求職信。 ``` const updateLetter = createCoverLetterAndResume.letter; ``` **步驟 2:** 使用 useMakeCopilotReadable 掛鉤新增 updateLetter 作為應用程式內聊天機器人的上下文。 ``` useMakeCopilotReadable("Cover Letter:" + JSON.stringify(updateLetter)); ``` **步驟 3:** 使用 useMakeCopilotActionable 掛鉤設定一個名為 updateCoverLetter 的操作,其中包含描述和實作函數,該函數使用提供的求職信更新來更新 createCoverLetterAndResume 狀態,如下所示。 ``` useMakeCopilotActionable( { name: "updateCoverLetter", description: "Update cover letter for a software developer job application.", argumentAnnotations: [ { name: "updateCoverLetterMarkdown", type: "string", description: "Update markdown text for a cover letter to introduce yourself and briefly summarize your professional background as a software developer.", required: true, }, { name: "resumeMarkdown", type: "string", description: "Markdown text for a resume that displays your professional background and relevant skills.", required: true, }, ], implementation: async (updatedCoverLetterMarkdown) => { setCreateCoverLetterAndResume((prevState) => ({ ...prevState, letter: updatedCoverLetterMarkdown, })); }, }, [] ); ``` ** 步驟 4:** 給聊天機器人一個提示,例如“更新求職信並加入我正在申請 CopilotKit 的技術寫作職位。”如下圖所示,您可以看到求職信已更新。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4dkm8zacgbmn19j9qtw6.png) --- ## 建立更新復原功能 **第 1 步:** 宣告一個名為 updateResume 的變數,用於保存先前產生的求職信。 ``` const updateResume = createCoverLetterAndResume.resume; ``` **步驟 2:** 使用 useMakeCopilotReadable 掛鉤新增 updateResume 作為應用程式內聊天機器人的上下文。 ``` useMakeCopilotReadable("Resume:" + JSON.stringify(updateResume)); ``` **步驟 3:** 使用 useMakeCopilotActionable 掛鉤設定一個名為 updateResume 的操作,其中包含描述和實作函數,該函數使用提供的求職信更新來更新 createCoverLetterAndResume 狀態,如下所示。 ``` useMakeCopilotActionable( { name: "updateResume", description: "Update resume for a software developer job application.", argumentAnnotations: [ { name: "updateResumeMarkdown", type: "string", description: "Update markdown text for a resume that displays your professional background and relevant skills.", required: true, }, ], implementation: async (updatedResumeMarkdown) => { setCreateCoverLetterAndResume((prevState) => ({ ...prevState, resume: updatedResumeMarkdown, })); }, }, [] ); ``` **第 4 步:** 向聊天機器人發出提示,例如「更新履歷並將我的姓名加入為 John Doe,將我的電子郵件加入為 [email protected]」。如下圖所示,可以看到履歷已更新。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2d9y6pmfynxwzff8be86.png) --- ## 建立下載求職信和履歷表 Pdfs 功能 **第 1 步:** 安裝 jsPDF,一個用 JavaScript 產生 PDF 的函式庫。 ``` npm i jspdf ``` **步驟 2:** 在 CoverLetterAndResume 元件內,使用 useMakeCopilotActionable 掛鉤設定一個名為“downloadPdfs”的操作,其中包含描述和實現函數,該函數使用 jsPDF 庫為求職信和簡歷建立 PDF,然後保存它們, 如下所示。 ``` function addTextToPDF(doc: any, text: any, x: any, y: any, maxWidth: any) { // Split the text into lines const lines = doc.splitTextToSize(text, maxWidth); // Add lines to the document doc.text(lines, x, y); } useMakeCopilotActionable( { name: "downloadPdfs", description: "Download pdfs of the cover letter and resume.", argumentAnnotations: [ { name: "coverLetterPdfA4", type: "string", description: "A Pdf that contains the cover letter converted from markdown text and fits A4 paper.", required: true, }, { name: "resumePdfA4Paper", type: "string", description: "A Pdf that contains the resume converted from markdown text and fits A4 paper.", required: true, }, ], implementation: async () => { const marginLeft = 10; const marginTop = 10; const maxWidth = 180; const coverLetterDoc = new jsPDF(); addTextToPDF( coverLetterDoc, createCoverLetterAndResume.letter, marginLeft, marginTop, maxWidth ); coverLetterDoc.save("coverLetter.pdf"); const resumeDoc = new jsPDF(); addTextToPDF( resumeDoc, createCoverLetterAndResume.resume, marginLeft, marginTop, maxWidth ); resumeDoc.save("resume.pdf"); }, }, [createCoverLetterAndResume] ); ``` **第 3 步:** 返回網頁應用程式中的聊天機器人,並提示「下載求職信和簡歷的 pdf 檔案」。 PDF 將開始下載,如果您開啟 coverLetter.pdf,您應該會看到產生的求職信,如下所示。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4p853urbqn43jh6454at.png) --- ## 結論 總而言之,您可以使用 CopilotKit 建立應用內 AI 聊天機器人,該機器人可以查看當前應用程式狀態並在應用程式內執行操作。 AI 聊天機器人可以與您的應用程式前端、後端和第三方服務對話。 對於完整的源程式碼: https://github.com/TheGreatBonnie/AIPoweredResumeBuilder --- 原文出處:https://dev.to/copilotkit/how-to-build-the-with-nextjs-openai-1mhb