🔍 搜尋結果:50'

🔍 搜尋結果:50'

如何讓 AI 融入您的使用者(Next.js、OpenAI、CopilotKit)

長話短說 ---- 在本文中,您將了解如何建立基於 AI 的行銷活動管理應用程式,該應用程式可讓您建立和分析廣告活動,從而使您能夠為您的業務做出正確的決策。 我們將介紹如何: - 使用 Next.js 建立 Web 應用程式, - 使用 CopilotKit 將 AI 助理整合到軟體應用程式中,以及 - 建立特定於操作的人工智慧副駕駛來處理應用程式中的各種任務。 - 建立一名競選經理 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9xqpz356qm79t90f1l87.gif) --- CopilotKit:建構應用內人工智慧副駕駛的框架 -------------------------- CopilotKit是一個[開源的AI副駕駛平台](https://github.com/CopilotKit/CopilotKit)。我們可以輕鬆地將強大的人工智慧整合到您的 React 應用程式中。 建造: - ChatBot:上下文感知的應用內聊天機器人,可以在應用程式內執行操作 💬 - CopilotTextArea:人工智慧驅動的文字字段,具有上下文感知自動完成和插入功能📝 - 聯合代理:應用程式內人工智慧代理,可以與您的應用程式和使用者互動🤖 ![https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3 .amazonaws.com%2Fuploads%2Farticles%2Fx3us3vc140aun0dvrdof.gif](https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fx3us3vc140aun0dvrdof.gif) {% cta https://git.new/devtoarticle1 %} Star CopilotKit ⭐️ {% endcta %} --- 先決條件 ---- 要完全理解本教程,您需要對 React 或 Next.js 有基本的了解。 我們還將利用以下內容: - [Radix UI](https://www.radix-ui.com/) - 用於為應用程式建立可存取的 UI 元件。 - [OpenAI API 金鑰](https://platform.openai.com/api-keys)- 使我們能夠使用 GPT 模型執行各種任務。 - [CopilotKit](https://github.com/CopilotKit/CopilotKit) - 一個開源副駕駛框架,用於建立自訂 AI 聊天機器人、應用程式內 AI 代理程式和文字區域。 --- 專案設定和套件安裝 --------- 首先,透過在終端機中執行以下程式碼片段來建立 Next.js 應用程式: ``` npx create-next-app campaign-manager ``` 選擇您首選的配置設定。在本教學中,我們將使用 TypeScript 和 Next.js App Router。 ![Next.js 應用程式安裝](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xboujt60i6lpoaqgjyap.png) 接下來,將[Heroicons](https://www.npmjs.com/package/@heroicons/react) 、 [Radix UI](https://www.radix-ui.com/)及其原始元件安裝到專案中。 ``` npm install @heroicons/react @radix-ui/react-avatar @radix-ui/react-dialog @radix-ui/react-dropdown-menu @radix-ui/react-icons @radix-ui/react-label @radix-ui/react-popover @radix-ui/react-select @radix-ui/react-slot @radix-ui/react-tabs ``` 另外,安裝[Recharts 程式庫](https://recharts.org/en-US)(一個用於建立互動式圖表的 React 程式庫)以及以下實用程式套件: ``` npm install recharts class-variance-authority clsx cmdk date-fns lodash react-day-picker tailwind-merge tailwindcss-animate ``` 最後,安裝[CopilotKit 軟體套件](https://docs.copilotkit.ai/getting-started/quickstart-chatbot)。這些套件使 AI copilot 能夠從 React 狀態檢索資料並在應用程式中做出決策。 ``` npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend ``` 恭喜!您現在已準備好建立應用程式。 --- 使用 Next.js 建立 Campaign Manager 應用程式 ----------------------------------- 在本節中,我將引導您建立活動管理器應用程式的使用者介面。 首先,讓我們進行一些初始設定。 在`src`資料夾中建立一個`components`和`lib`資料夾。 ``` cd src mkdir components lib ``` 在**`lib`**資料夾中,我們將聲明應用程式的靜態類型和預設活動。因此,在**`lib`**資料夾中建立**`data.ts`**和**`types.ts`**檔案。 ``` cd lib touch data.ts type.ts ``` 將下面的程式碼片段複製到`type.ts`檔中。它聲明了活動屬性及其資料類型。 ``` export interface Campaign { id: string; objective?: | "brand-awareness" | "lead-generation" | "sales-conversion" | "website-traffic" | "engagement"; title: string; keywords: string; url: string; headline: string; description: string; budget: number; bidStrategy?: "manual-cpc" | "cpa" | "cpm"; bidAmount?: number; segment?: string; } ``` 為應用程式建立預設的行銷活動清單並將其複製到`data.ts`檔案中。 ``` import { Campaign } from "./types"; export let DEFAULT_CAMPAIGNS: Campaign[] = [ { id: "1", title: "CopilotKit", url: "https://www.copilotkit.ai", headline: "Copilot Kit - The Open-Source Copilot Framework", description: "Build, deploy, and operate fully custom AI Copilots. In-app AI chatbots, AI agents, AI Textareas and more.", budget: 10000, keywords: "AI, chatbot, open-source, copilot, framework", }, { id: "2", title: "EcoHome Essentials", url: "https://www.ecohomeessentials.com", headline: "Sustainable Living Made Easy", description: "Discover our eco-friendly products that make sustainable living effortless. Shop now for green alternatives!", budget: 7500, keywords: "eco-friendly, sustainable, green products, home essentials", }, { id: "3", title: "TechGear Solutions", url: "https://www.techgearsolutions.com", headline: "Innovative Tech for the Modern World", description: "Find the latest gadgets and tech solutions. Upgrade your life with smart technology today!", budget: 12000, keywords: "tech, gadgets, innovative, modern, electronics", }, { id: "4", title: "Global Travels", url: "https://www.globaltravels.com", headline: "Travel the World with Confidence", description: "Experience bespoke travel packages tailored to your dreams. Luxury, adventure, relaxation—your journey starts here.", budget: 20000, keywords: "travel, luxury, adventure, tours, global", }, { id: "5", title: "FreshFit Meals", url: "https://www.freshfitmeals.com", headline: "Healthy Eating, Simplified", description: "Nutritious, delicious meals delivered to your door. Eating well has never been easier or tastier.", budget: 5000, keywords: "healthy, meals, nutrition, delivery, fit", }, ]; ``` 由於我們使用 Radix UI 建立可以使用 TailwindCSS 輕鬆自訂的基本 UI 元件,因此請在**`lib`**資料夾中建立一個**`utils.ts`**文件,並將以下程式碼片段複製到該文件中。 ``` //👉🏻 The lib folder now contains 3 files - data.ts, type.ts, util.ts //👇🏻 Copy the code below into the "lib/util.ts" file. import { type ClassValue, clsx } from "clsx"; import { twMerge } from "tailwind-merge"; export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)); } export function randomId() { return Math.random().toString(36).substring(2, 15); } ``` 導航到`components`資料夾並在其中建立其他三個資料夾。 ``` cd components mkdir app dashboard ui ``` `components/app`資料夾將包含應用程式中使用的各種元件,而儀表板資料夾包含某些元素的 UI 元件。 `ui`資料夾包含使用 Radix UI 建立的多個 UI 元素。將[專案儲存庫中的這些元素](https://github.com/CopilotKit/campaign-manager-demo/tree/main/src/components/ui)複製到該資料夾中。 恭喜! `ui`資料夾應包含必要的 UI 元素。現在,我們可以使用它們來建立應用程式中所需的各種元件。 ### 建立應用程式 UI 元件 在這裡,我將引導您完成為應用程式建立使用者介面的過程。 ![應用程式使用者介面](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9l4lvv4394gg033oatwq.png) 首先,導航至**`app/page.tsx`**檔案並將以下程式碼片段貼到其中。該文件呈現在**`components/app`**資料夾中聲明的 App 元件。 ``` "use client"; import { App } from "@/components/app/App"; export default function DashboardPage() { return <App />; } ``` 在`components/app`資料夾中建立`App.tsx` 、 `CampaignForm.tsx` 、 `MainNav.tsx`和`UserNav.tsx`檔案。 ``` cd components/app touch App.tsx CampaignForm.tsx MainNav.tsx UserNav.tsx ``` 將下面的程式碼片段複製到`App.tsx`檔案中。 ``` "use client"; import { DEFAULT_CAMPAIGNS } from "@/lib/data"; import { Campaign } from "@/lib/types"; import { randomId } from "@/lib/utils"; import { Dashboard } from "../dashboard/Dashboard"; import { CampaignForm } from "./CampaignForm"; import { useState } from "react"; import _ from "lodash"; export function App() { //👇🏻 default segments const [segments, setSegments] = useState<string[]>([ "Millennials/Female/Urban", "Parents/30s/Suburbs", "Seniors/Female/Rural", "Professionals/40s/Midwest", "Gamers/Male", ]); const [campaigns, setCampaigns] = useState<Campaign[]>( _.cloneDeep(DEFAULT_CAMPAIGNS) ); //👇🏻 updates campaign list function saveCampaign(campaign: Campaign) { //👇🏻 newly created campaign if (campaign.id === "") { campaign.id = randomId(); setCampaigns([campaign, ...campaigns]); } else { //👇🏻 existing campaign - search for the campaign and updates the campaign list const index = campaigns.findIndex((c) => c.id === campaign.id); if (index === -1) { setCampaigns([...campaigns, campaign]); } else { campaigns[index] = campaign; setCampaigns([...campaigns]); } } } const [currentCampaign, setCurrentCampaign] = useState<Campaign | undefined>( undefined ); return ( <div className='relative'> <CampaignForm segments={segments} currentCampaign={currentCampaign} setCurrentCampaign={setCurrentCampaign} saveCampaign={(campaign) => { if (campaign) { saveCampaign(campaign); } setCurrentCampaign(undefined); }} /> <Dashboard campaigns={campaigns} setCurrentCampaign={setCurrentCampaign} segments={segments} setSegments={setSegments} /> </div> ); } ``` - 從上面的程式碼片段來看, - 我為行銷活動建立了預設細分列表,並對已定義的行銷活動列表進行了深層複製。 - `saveCampaign`函數接受行銷活動作為參數。如果行銷活動沒有 ID,則表示它是新建立的,因此會將其新增至行銷活動清單。否則,它會找到該活動並更新其屬性。 - `Dashboard`和`CampaignForm`元件接受細分和行銷活動作為 props。 [Dashboard 元件](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/components/dashboard/Dashboard.tsx)在儀表板上顯示各種 UI 元素,而[CampaignForm 元件](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/components/app/CampaignForm.tsx)使用戶能夠在應用程式中建立和保存新的行銷活動。 您也可以使用[GitHub 儲存庫](https://github.com/CopilotKit/campaign-manager-demo/tree/main/src/components)中的程式碼片段來更新儀表板和應用程式元件。 恭喜!您應該有一個有效的 Web 應用程式,可讓使用者查看和建立新的行銷活動。 在接下來的部分中,您將了解如何將 CopilotKit 加入到應用程式中,以根據每個行銷活動的目標和預算進行分析和決策。 ![應用概述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4phyaucli8pdcbe625u4.gif) --- 使用 CopilotKit 透過 AI 分析廣告活動 -------------------------- 在這裡,您將學習如何將人工智慧加入到應用程式中,以幫助您分析行銷活動並做出最佳決策。 在繼續之前,請造訪[OpenAI 開發者平台](https://platform.openai.com/api-keys)並建立一個新的金鑰。 ![取得 OpenAI API 金鑰](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/02972pt2aj3kf9l5suqq.png) 建立一個`.env.local`檔案並將新建立的金鑰複製到該檔案中。 ``` OPENAI_API_KEY=<YOUR_OPENAI_SECRET_KEY> OPENAI_MODEL=gpt-4-1106-preview ``` 接下來,您需要為 CopilotKit 建立 API 端點。在 Next.js 應用程式資料夾中,建立一個包含`route.ts`檔案的`api/copilotkit`資料夾。 ``` cd app mkdir api && cd api mkdir copilotkit && cd copilotkit touch route.ts ``` 將下面的程式碼片段複製到`route.ts`檔中。 [CopilotKit 後端](https://docs.copilotkit.ai/reference/CopilotBackend)接受使用者的請求並使用 OpenAI 模型做出決策。 ``` import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; export const runtime = "edge"; export async function POST(req: Request): Promise<Response> { const copilotKit = new CopilotBackend({}); const openaiModel = process.env["OPENAI_MODEL"]; return copilotKit.response(req, new OpenAIAdapter({ model: openaiModel })); } ``` 若要將您的應用程式連接到此 API 端點,請更新`app/page.tsx`文件,如下所示: ``` "use client"; import { App } from "@/components/app/App"; import { CopilotKit } from "@copilotkit/react-core"; import { CopilotSidebar } from "@copilotkit/react-ui"; export default function DashboardPage() { return ( <CopilotKit url='/api/copilotkit/'> <CopilotSidebar instructions='Help the user create and manage ad campaigns.' defaultOpen={true} labels={{ title: "Campaign Manager Copilot", initial: "Hello there! I can help you manage your ad campaigns. What campaign would you like to work on?", }} clickOutsideToClose={false} > <App /> </CopilotSidebar> </CopilotKit> ); } ``` `CopilotKit`元件包裝整個應用程式並接受包含 API 端點連結的`url`屬性。 `CopilotSidebar`元件為應用程式加入了一個聊天機器人側邊欄面板,使我們能夠向 CopilotKit 提供各種指令。 ![將 CopilotKit 加入 Next.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wzh8ui253ftzmgtrcksd.gif) ### 如何讓AI副駕駛執行各種動作 CopilotKit 提供了兩個鉤子,使我們能夠處理使用者的請求並插入應用程式狀態: [useCopilotAction](https://docs.copilotkit.ai/reference/useCopilotAction)和[useMakeCopilotReadable](https://docs.copilotkit.ai/reference/useMakeCopilotReadable) 。 `useCopilotAction`掛鉤可讓您定義 CopilotKit 執行的動作。它接受包含以下參數的物件: - name - 操作的名稱。 - 描述 - 操作的描述。 - 參數 - 包含所需參數清單的陣列。 - 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`掛鉤向 CopilotKit 提供應用程式狀態。 ``` import { useMakeCopilotReadable } from "@copilotkit/react-core"; const appState = ...; useMakeCopilotReadable(JSON.stringify(appState)); ``` CopilotKit 還允許您為使用者提示提供上下文,使其能夠做出充分且準確的決策。 將`guidance.ts`和`script.ts`加入到專案內的`lib`資料夾中,並將此[指導](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/lib/guideline.ts)和[腳本建議](https://github.com/CopilotKit/campaign-manager-demo/blob/main/src/lib/script.ts)複製到檔案中,以便 CopilotKit 做出決策。 在應用程式元件中,將當前日期、腳本建議和指導傳遞到 CopilotKit。 ``` import { GUIDELINE } from "@/lib/guideline"; import { SCRIPT_SUGGESTION } from "@/lib/script"; import { useCopilotAction, useMakeCopilotReadable, } from "@copilotkit/react-core"; export function App() { //-- 👉🏻 ...other component functions //👇🏻 Ground the Copilot with domain-specific knowledge for this use-case: marketing campaigns. useMakeCopilotReadable(GUIDELINE); useMakeCopilotReadable(SCRIPT_SUGGESTION); //👇🏻 Provide the Copilot with the current date. useMakeCopilotReadable("Today's date is " + new Date().toDateString()); return ( <div className='relative'> <CampaignForm segments={segments} currentCampaign={currentCampaign} setCurrentCampaign={setCurrentCampaign} saveCampaign={(campaign) => { if (campaign) { saveCampaign(campaign); } setCurrentCampaign(undefined); }} /> <Dashboard campaigns={campaigns} setCurrentCampaign={setCurrentCampaign} segments={segments} setSegments={setSegments} /> </div> ); } ``` 在`App`元件中建立一個 CopilotKit 操作,該操作可在使用者提供此類指令時建立新的活動或編輯現有的活動。 ``` useCopilotAction({ name: "updateCurrentCampaign", description: "Edit an existing campaign or create a new one. To update only a part of a campaign, provide the id of the campaign to edit and the new values only.", parameters: [ { name: "id", description: "The id of the campaign to edit. If empty, a new campaign will be created", type: "string", }, { name: "title", description: "The title of the campaign", type: "string", required: false, }, { name: "keywords", description: "Search keywords for the campaign", type: "string", required: false, }, { name: "url", description: "The URL to link the ad to. Most of the time, the user will provide this value, leave it empty unless asked by the user.", type: "string", required: false, }, { name: "headline", description: "The headline displayed in the ad. This should be a 5-10 words", type: "string", required: false, }, { name: "description", description: "The description displayed in the ad. This should be a short text", type: "string", required: false, }, { name: "budget", description: "The budget of the campaign", type: "number", required: false, }, { name: "objective", description: "The objective of the campaign", type: "string", enum: [ "brand-awareness", "lead-generation", "sales-conversion", "website-traffic", "engagement", ], }, { name: "bidStrategy", description: "The bid strategy of the campaign", type: "string", enum: ["manual-cpc", "cpa", "cpm"], required: false, }, { name: "bidAmount", description: "The bid amount of the campaign", type: "number", required: false, }, { name: "segment", description: "The segment of the campaign", type: "string", required: false, enum: segments, }, ], handler: (campaign) => { const newValue = _.assign( _.cloneDeep(currentCampaign), _.omitBy(campaign, _.isUndefined) ) as Campaign; setCurrentCampaign(newValue); }, render: (props) => { if (props.status === "complete") { return "Campaign updated successfully"; } else { return "Updating campaign"; } }, }); ``` {% 嵌入 https://www.youtube.com/watch?v=gCJpH6Tnj5g %} 新增另一個模擬 API 呼叫的操作,以允許 CopilotKit 從先前建立的活動中檢索歷史資料。 ``` // Provide this component's Copilot with the ability to retrieve historical cost data for certain keywords. // Will be called automatically when needed by the Copilot. useCopilotAction({ name: "retrieveHistoricalData", description: "Retrieve historical data for certain keywords", parameters: [ { name: "keywords", description: "The keywords to retrieve data for", type: "string", }, { name: "type", description: "The type of data to retrieve for the keywords.", type: "string", enum: ["CPM", "CPA", "CPC"], }, ], handler: async ({ type }) => { // fake an API call that retrieves historical data for cost for certain keywords based on campaign type (CPM, CPA, CPC) await new Promise((resolve) => setTimeout(resolve, 2000)); function getRandomValue(min: number, max: number) { return (Math.random() * (max - min) + min).toFixed(2); } if (type == "CPM") { return getRandomValue(0.5, 10); } else if (type == "CPA") { return getRandomValue(5, 100); } else if (type == "CPC") { return getRandomValue(0.2, 2); } }, render: (props) => { // Custom in-chat component rendering. Different components can be rendered based on the status of the action. let label = "Retrieving historical data ..."; if (props.args.type) { label = `Retrieving ${props.args.type} for keywords ...`; } if (props.status === "complete") { label = `Done retrieving ${props.args.type} for keywords.`; } const done = props.status === "complete"; return ( <div className=''> <div className=' w-full relative max-w-xs'> <div className='absolute inset-0 h-full w-full bg-gradient-to-r from-blue-500 to-teal-500 transform scale-[0.80] bg-red-500 rounded-full blur-3xl' /> <div className='relative shadow-xl bg-gray-900 border border-gray-800 px-4 py-8 h-full overflow-hidden rounded-2xl flex flex-col justify-end items-start'> <h1 className='font-bold text-sm text-white mb-4 relative z-50'> {label} </h1> <p className='font-normal text-base text-teal-200 mb-2 relative z-50 whitespace-pre'> {props.args.type && `Historical ${props.args.type}: ${props.result || "..."}`} </p> </div> </div> </div> ); }, }); ``` ![應用程式預覽](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kz3xm63ciq5q3kyooz9s.gif) 恭喜!您已完成本教學的專案。 結論 -- [CopilotKit](https://copilotkit.ai/)是一款令人難以置信的工具,可讓您在幾分鐘內將 AI Copilot 加入到您的產品中。無論您是對人工智慧聊天機器人和助理感興趣,還是對複雜任務的自動化感興趣,CopilotKit 都能讓您輕鬆實現。 如果您需要建立 AI 產品或將 AI 工具整合到您的軟體應用程式中,您應該考慮 CopilotKit。 您可以在 GitHub 上找到本教學的源程式碼: <https://github.com/CopilotKit/campaign-manager-demo> 感謝您的閱讀! --- 原文出處:https://dev.to/copilotkit/build-an-ai-powered-campaign-manager-nextjs-openai-copilotkit-59ii

📚 前 1% 的 React 開發者使用的 8 個儲存庫 🏆

你好👋 今天,讓我們來看看**前 1% 的開發人員使用**的 8 個 React 儲存庫(以及那些您可能從未聽說過的儲存庫)。 準備好? ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5yehweju0i54ov2n6bwt.gif) --- # 我們如何找到前 1% 的開發人員使用的儲存庫? 🔦 我們如何找到最好的開發人員使用的東西背後的故事植根於大量的資料探勘和一些重要的建模。 現在,在 Quine,我們根據開發人員的**[DevRank](https://docs.quine.sh/for-developers/devrank)** 對開發人員進行排名。 簡單來說,DevRank 使用 [Google 的 PageRank 演算法](https://en.wikipedia.org/wiki/PageRank) 根據開發人員對開源儲存庫的貢獻來衡量開發人員在開源領域的重要性。 為了建立此列表,我們查看了前 1% 已加星號的儲存庫。 🌟 然後,我們計算了前 1% 的開發者會為回購加註星標的可能性,與後 50% 的開發者不支持的可能性進行比較。 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/miugcnqpataix1fsq6hb.png) 最後,經過一番挑選,我們找到了以下 8 個儲存庫。 :向下點: 當您想要建立很酷的網頁應用程式時,這些儲存庫將特別有用。** 如果您有興趣建立小型應用程式,並且喜歡應用人工智慧方面,我們建議您查看 Creator Quests,這是一項**開源挑戰,獎勵開發人員使用 ChatGPT、Claude、Gemini 建立酷炫的 GenerativeAI 應用程式**和更多。 :upside_down_face: 💰 最新的 Creator Quest 挑戰您使用生成式 AI 建立開發人員工具。要參與,只需註冊 [Quine](https://quine.sh/?utm_source=devto&utm_campaign=best_react_repos) 並前往 _Quests_。 **目前獎金池為$2028**,並且隨著更多參與者的加入,獎金池將會增加!點擊下面的圖片並嘗試! ⬇️ [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/akiuhk62zctvf3b9gilx.png)](https://quine.sh/?utm_source=devto&utm_campaign=best_react_repos) --- # jsxstyle/jsxstyle **不再有 JS 到 CSS 的跳躍** [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h75mskqja5bcwst05e93.png)](https://github.com/jsxstyle/jsxstyle) **為什麼要關心?** 在 Web 開發中,使用 React 或 Preact,您必須設定元件的樣式(如按鈕、選單等)。傳統上,這是使用單獨的 CSS 檔案或複雜的樣式系統來完成的,這可能非常耗時且管理起來很麻煩。 jsxstyle 可讓您直接在 JavaScript 程式碼中以及元件中定義樣式,從而簡化了此過程。換句話說,這意味著您不再需要在 JS 和 CSS 檔案之間跳躍。 **設定**:`npm install jsxstyle` **範例用例**:您的程式碼可以如下所示。 👇 ``` <Row padding={15}> <Block backgroundColor="#EEE" boxShadow="inset 0 0 0 1px rgba(0,0,0,0.15)" borderRadius={5} height={64} width={64} marginRight={15} backgroundSize="contain" backgroundImage="url(http://graph.facebook.com/justinbieber/picture?type=large)" /> <Col fontFamily="sans-serif" fontSize={16} lineHeight="24px"> <Block fontWeight={600}>Justin Bieber</Block> <Block fontStyle="italic">Canadian</Block> </Col> </Row> ``` [https://github.com/jsxstyle/jsxstyle](https://github.com/jsxstyle/jsxstyle) --- # 💨 alangpierce/蔗糖酶 **Babel 的超快替代品** [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rk9ceq6mlw8ya0f2icb8.png)](https://github.com/alangpierce/sucrase) **為什麼你應該關心?** Babel 是 Web 開發中廣泛使用的工具,可將現代 JavaScript 程式碼轉換為舊瀏覽器可以理解的格式。 Sucrase 是 Babel 更快的替代品。 **設定**: ``` yarn add --dev sucrase # Or npm install --save-dev sucrase node -r sucrase/register main.ts ``` **用例範例**:Sucrase 可以直接從 JS 呼叫: ``` import {transform} from "sucrase"; const compiledCode = transform(code, {transforms: ["typescript", "imports"]}).code; ``` [https://github.com/alangpierce/sucrase](https://github.com/alangpierce/sucrase) --- # 🎨 woorm/折射鏡 **我為您的網頁程式碼著色,讓您的生活更輕鬆** [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hzwpgi5t47o93kvcbtdq.png)](https://github.com/wooorm/refractor) **為什麼你應該關心?** Refractor 很重要,因為它允許您加入突出顯示,從而增強專案的可讀性;尤其是當您將程式碼片段新增至 Web 應用程式時。它允許您用 270 多種程式語言表達程式碼,並且在傳統的基於 HTML 的突出顯示不理想的領域(例如 CLI 表單)特別有用。 **設定**:`npm install refractor` **用例範例**: ``` import {refractor} from 'refractor' const tree = refractor.highlight('"use strict";', 'js') console.log(tree) ``` **產量**: ``` { type: 'root', children: [ { type: 'element', tagName: 'span', properties: {className: ['token', 'string']}, children: [{type: 'text', value: '"use strict"'}] }, { type: 'element', tagName: 'span', properties: {className: ['token', 'punctuation']}, children: [{type: 'text', value: ';'}] } ] } ``` [https://github.com/wooorm/refractor](https://github.com/wooorm/refractor) --- # 🐦 react-static-tweets **您在網站上加入推文的最佳選擇。** [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1lvul78znx84ph479fa1.png)](https://github.com/transitive-bullshit/react-static-tweets) **為什麼你應該關心?** 將推文加入到您的網站是您在許多登陸頁面上看到的一項很酷的功能。 React Static Tweets 很重要,因為它提供了一種在 Web 專案中嵌入推文的高效方法,與 Twitter 的標準嵌入方法相比,提供更快的載入時間和更好的效能。 **設定**: ``` npm install react-static-tweets static-tweets date-fns # or yarn add react-static-tweets static-tweets date-fns ``` **用例範例:** ``` import React from 'react' import { fetchTweetAst } from 'static-tweets' import { Tweet } from 'react-static-tweets' const tweetId = '1358199505280262150' export const getStaticProps = async () => { try { const tweetAst = await fetchTweetAst(tweetId) return { props: { tweetAst }, revalidate: 10 } } catch (err) { console.error('error fetching tweet', err) throw err } } export default function Example({ tweetAst }) { return <Tweet ast={tweetAst} /> } ``` [https://github.com/transitive-bullshit/react-static-tweets](https://github.com/transitive-bullshit/react-static-tweets) --- # 🖨️ preactjs/preact-render-to-string **以 HTML 形式呈現您的元件** [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m7djwj6w7nqwfnifc43c.png)](https://github.com/preactjs/preact-render-to-string) **為什麼要關心?** 「preact-render-to-string」是一個工具,可以幫助網站更快地載入並在搜尋引擎中更好地顯示。使用 Preact 等 JS 框架建立的網站需要一段時間才能顯示內容,因為瀏覽器必須先執行 JavaScript。此儲存庫透過將元件轉換為現成的 HTML 來完成伺服器端的繁重工作。因此,當有人造訪該網站時,即使網路速度很慢,他們也會立即看到內容。 **設定**:`npm install preact-render-to-string` **用例範例:** ``` import { render } from 'preact-render-to-string'; import { h, Component } from 'preact'; /** @jsx h */ // Classical components work class Fox extends Component { render({ name }) { return <span class="fox">{name}</span>; } } // ... and so do pure functional components: const Box = ({ type, children }) => ( <div class={`box box-${type}`}>{children}</div> ); let html = render( <Box type="open"> <Fox name="Finn" /> </Box> ); console.log(html); // <div class="box box-open"><span class="fox">Finn</span></div> ``` [https://github.com/preactjs/preact-render-to-string](https://github.com/preactjs/preact-render-to-string) --- # 🏆 自行車刮鬍/曲柄 **唯一的 JavaScript 框架** [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l8hp1ex1qh1sv6isksaq.png)](https://github.com/bikeshaving/crank) **為什麼要關心?** 在像 React 這樣的傳統 Web 框架中,Web 元件配置一次,僅在明確指定時才更改。它們看起來像是需要手動更新的靜態影像。 Crank.js 透過允許小部件更新自身以回應新資料來改變這一點,類似於用新新聞刷新的新聞收報機。這對於管理即時資料(例如即時體育賽事比分或產品更新)的 Web 應用程式尤其有用。 這個倉庫需要更多的人遷移到這裡才能獲得關注,但它仍然是一個非常酷的倉庫,值得關注。 👀 **設定**:`$ npm i @b9g/crank` **用例範例**: ``` import {renderer} from "@b9g/crank/dom"; function Greeting({name = "World"}) { return ( <div>Hello {name}</div> ); } renderer.render(<Greeting />, document.body); ``` [https://github.com/bikeshaving/crank](https://github.com/bikeshaving/crank) --- # 🎯 evoluhq/evolu **我是一個本地第一的人** [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k15m25pi0w9pk0g54zrn.png)](https://github.com/evoluhq/evolu) **為什麼要關心?** Web 應用程式通常依賴在伺服器上儲存使用者資料,這需要持續的網路連接,並引起對隱私和資料安全的擔憂。這種基於伺服器的方法也意味著如果伺服器發生故障或公司停止運營,效能會降低,並且可能會遺失資料。 Evolu 引入了「本地優先」方法,其中資料直接儲存在使用者的裝置上。這意味著您的應用程式可以離線工作,更快地存取資料,並提供增強的隱私和安全性。如果您正在建立離線 Chrome/瀏覽器應用程式,這將非常有用。 **設定**:` npm install @evolu/react` 要開始使用它,您可以在[此處](https://www.evolu.dev/docs/quickstart)找到這個很棒的指南。 [https://github.com/evoluhq/evolu](https://github.com/evoluhq/evolu) --- # 📸 笑話社群/快照差異 **我比較你們的元件並突出顯示差異** [![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hy76comkwkqkt0d5qn8z.png)](https://github.com/jest-community/snapshot-diff) **為什麼要關心?** 在測試 React 元件或其他 JavaScript 值時,開發人員通常會比較整個狀態或輸出。這意味著處理大量資料,查找特定變更就像大海撈針一樣。 Snapshot-diff 是重點比較工具,可讓您取得元件的兩種不同狀態(或任兩個 JavaScript 值)並直接比較它們,僅將差異突出顯示。 這對於測試 React 元件特別有幫助,因為它可以準確指出兩種狀態之間發生的變化,從而更容易辨識和理解程式碼變更的影響。 **設定**:`yarn add --dev snapshot-diff` **範例用例:** 預設笑話匹配器 ``` const snapshotDiff = require('snapshot-diff'); test('snapshot difference between 2 strings', () => { expect(snapshotDiff(a, b)).toMatchSnapshot(); }); const React = require('react'); const Component = require('./Component'); test('snapshot difference between 2 React components state', () => { expect( snapshotDiff(<Component test="say" />, <Component test="my name" />) ).toMatchSnapshot(); }); ``` [https://github.com/jest-community/snapshot-diff](https://github.com/jest-community/snapshot-diff) --- **我希望這些發現對您有價值,並將有助於建立更強大的 React 工具包!⚒️** 如果您今天想利用這些工具來獲得獎勵,我們剛剛發起了一項使用生成式人工智慧建立開發人員工具的挑戰。 如果對此有興趣,請登入 [Quine](https://quine.sh/?utm_source=devto&utm_campaign=best_react_repos) 並發現任務! 💰 ![圖片描述](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/o5drisgbolxfnzfvtwzw.gif) 最後,請**考慮透過加星號來支持這些專案。 ⭐️** PS:我們與他們沒有任何關係。我們只是認為偉大的專案值得高度認可。 下週見, 您的開發夥伴💚 巴普 --- 原文出處:https://dev.to/quine/8-repos-used-by-the-top-1-of-react-devs-2758