🔍 搜尋結果:CD

🔍 搜尋結果:CD

我推薦 Svelte 給所有工程師的 10 個理由

原文出處:https://dev.to/mhatvan/10-reasons-why-i-recommend-svelte-to-every-new-web-developer-nh3 儘管 [Svelte](https://svelte.dev/) 的初始版本早在 2016 年 11 月就發布了,但它在 JavaScript 前端框架中仍然處於劣勢,並且最近才開始受到社區應有的關注。 在使用了多年的各種 JavaScript 框架(包括 Angular、React 和 Vue.js)之後,我認為我對編寫程式碼如何愉快以及如何令人沮喪有了良好的總體印象。 幾年前,使用 [jQuery](https://jquery.com/) 編寫程式碼感覺就像來自純 JavaScript 的啟示。然後在我的第一份工作中,我開始使用 Angular 2,突然間 jQuery 感覺像是一個拖累。現在,React 是最酷的孩子,相比之下,Angular 感覺太複雜了。您可能會看到這是怎麼回事! 對我來說,Svelte 是快速變化的 JavaScript 框架生態系統中的下一個進化步驟。用 Svelte 的方式編寫感覺很容易,你可以看出它的建立者 [Rich Harris](https://twitter.com/Rich_Harris)厭倦了現有框架要求您學習的所有煩人的抽象和必要的樣板程式碼。 現在你可能會問自己這個問題: ## 是什麼讓 Svelte 與眾不同? 您可能聽說過 Svelte 出現在諸如 [前端框架的真實世界比較](https://medium.com/dailyjs/a-realworld-comparison-of-front-end-frameworks-2020-4e50655fe4c1) 和 [State of JS Survey](https://2019.stateofjs.com/front-end-frameworks/) 等開發人員調查將其列為在捆綁包大小、性能、程式碼行數方面排名最好的框架之一以及最重要的開發者滿意度。 與流行的 [React](https://reactjs.org/) 和 [Vue.js](https://vuejs.org/) 庫相比,它們在執行時執行大量工作並使用一種稱為“虛擬”的技術DOM diffing”用於檢測變化,Svelte 作為建置步驟被編譯成無框架的 vanilla JavaScript,因此可以從大量程式碼優化中受益。 出於本能的猶豫,我起初將 Svelte 視為“只是另一個 JavaScript 框架”而不予考慮,也沒有費心去研究它。第二次聽說後,我想知道:Svelte 是炒作還是真的那麼好?我決定對它進行實戰測試並將其用於我的個人專案。 現在幾個月後,我可以給你一個明確的答案: ## Svelte 簡單、強大且優雅,您會愛上它! 事不宜遲,以下是我向每位開始學習編程的新 Web 開發人員推薦 Svelte 的十大理由: ## 1. Svelte 元件易於理解 如果您以前從未見過 Svelte 語法,這就是一個簡單示例的樣子: https://gist.github.com/mhatvan/3630989d364e4020f26ebb96d2d7c332 與其他引入大量抽象概念、需要花時間學習和理解的前端框架相比,看到 Svelte 只是並排使用普通的舊 HTML、CSS 和 JavaScript,真是令人耳目一新。您可以通過其對初學者友好的語法查看並輕鬆辨識此處發生的情況。 ## 2.簡單寫簡潔的程式碼 正如您在上面的程式碼示例中看到的,您編寫的業務邏輯既簡單又易於閱讀。畢竟,您編寫的程式碼越少,錯誤就越少,對吧? Svelte 的天才創造者 Rich Harris 在他的文章 [少寫程式碼](https://svelte.dev/blog/write-less-code) 中對 React 和 Vue.js 進行了一些很好的比較。根據他對編寫簡單的兩個數字相加邏輯所需的字符的檢查,React 元件通常比其 Svelte 元件大 40% 左右! ## 3. 與標記語句的反應性 每當您希望根據其他變數更新和重新計算變數值時,您可以使用反應式聲明。只需在您想要響應的變數前面放一個美元符號,您就可以開始了! https://gist.github.com/mhatvan/7e2f0fea362c79d64a34cb7e0c088453 每次單擊按鈕時,`count` 將增加 1,而 `doubled` 將知道 `count` 的值發生變化並相應地更新。從反應性的角度思考真的很有趣,而且寫起來感覺很好。 ## 4.開箱即用的簡單全局狀態管理 無需任何復雜的第三方狀態管理工具,如 [Redux](https://redux.js.org/) 或 [Vuex](https://vuex.vuejs.org/)。 您只需將一個變數定義為可寫/可讀存儲,並在任何以 `$` 符號為前綴的 `.svelte` 文件中使用它。 https://gist.github.com/mhatvan/710b6bb6df4ece7e9a5f53886eb2dd0d 在此示例中,我們檢查當前環境,它作為值存在於我們的商店中,並使用它來決定是否應顯示 cookie 通知。很簡單,不是嗎? 使用 Svelte 存儲,您也永遠不必擔心內存洩漏,因為以 `$` 符號為前綴的存儲變數充當自動訂閱和自動取消訂閱。 ## 5. 內置可存取性和未使用的 CSS 檢查 Svelte 希望讓網路變得更美好,並通過程式碼中的有用提示幫助您。 每當您忘記將 alt 屬性放在 `<img>` 標籤上時,Svelte 都會為您顯示 `A11y: <img> 元素應該有一個 alt 屬性` 提醒。在 Svelte 中實現了一長串可存取性檢查,它們會提示您而不會成為麻煩。 為了使程式碼盡可能簡潔並避免遺留程式碼片段,只要在元件中找不到相應的標記,Svelte 還會為您標記未使用的 CSS 選擇器。 ## 6.元件自動導出 每當你想在元件 B 中使用元件 A 時,你通常需要先編寫程式碼導出元件 A,這樣它才能被元件 B 導入。使用 Svelte,你永遠不必擔心忘記導出, `.svelte` 元件始終默認自動為您導出,並準備好由任何其他元件導入。 ## 7. 默認情況下樣式是有範圍的 類似於 [CSS-in-JS](https://webdesign.tutsplus.com/articles/an-introduction-to-css-in-js-examples-pros-and-cons--cms-33574) 庫,Svelte默認情況下,樣式是有範圍的,這意味著 `svelte-<unique-hash>` 類名將附加到您的樣式,因此它們不會洩漏和影響任何其他元件樣式。當然,您可以選擇全局應用樣式,只需在它們前面加上 `:global()` 修飾符,或者如果您願意,也可以只使用 `.css` 文件。 ## 8. #await 塊 對於大多數 Web 應用程式,您將需要處理異步資料以向用戶顯示有用的統計訊息。 https://gist.github.com/mhatvan/2e44dc1ec402f477830f90bd77614f34 `{#await}` 塊的優點是您不必為已解決/拒絕的承諾定義額外的狀態,您只需在模板中定義內聯變數即可。 ## 9.傳遞道具的速記屬性 如果存在與變數名稱相同的 prop 名稱,我們可以將其作為簡寫屬性傳遞給元件,如下面的“{message}”。與使用 `message="{message}"` 相比沒有任何優勢,但更簡潔。 https://gist.github.com/mhatvan/9085f5330eeccdc2238e4f4e609b4f88 在上方,您可以看到根據 round 是真還是假將 class:round 屬性應用於按鈕。這很容易成為一個可重用的元件,您可以從外部傳遞 `round` 的值來有條件地決定元件的樣式。 ## 10.內置效果和動畫 Svelte 預裝了強大的效果模塊: - `svelte/motion` 效果,如補間和彈簧 - `svelte/transition` 效果,如淡入淡出、模糊、飛行、滑動、縮放、繪製 - `svelte/animate` 效果如翻轉 - `svelte/easing` 效果,如彈跳、立方體、彈性等等 Svelte 官方教程中有幾個示例,但我最喜歡[這個進度條示例](https://svelte.dev/tutorial/tweened),因為它很簡單。 動畫是 web 開發的一個領域,您通常會在其中尋找外部依賴項來為您處理它,因此您可以開箱即用地使用它們真是太好了。 ## 不採用 Svelte 的合理理由 為了避免讓這篇文章聽起來像一篇冗長的狂熱帖子,以下是我迄今為止使用 Svelte 時遇到的缺點: ### `.svelte` 文件不能導出多個元件 一方面,我們受益於默認自動導出的 .svelte 文件,但這也意味著我們無法從單個文件導出多個元件。我不認為這有什麼大不了的,因為它會迫使您遵循最佳實踐來使用許多小的獨立元件編寫您的應用程式,這使它們易於理解和單元測試。 ### 一般模板語法 為了顯示條件邏輯,Svelte 使用類似於眾所周知的 [Handlebars](https://handlebarsjs.com/guide/builtin-helpers.html#if) 模板語法的語法。 https://gist.github.com/mhatvan/95cc1837441a272cb8422fcae24d91e0 這種編寫邏輯的方式我沒有遇到任何問題,但我更喜歡更簡潔的語法。 ### 使用 export let 在子元件中接收 props 當您想要將值從父元件傳遞到子元件時,您需要將一個值作為屬性傳遞,並使用帶有匹配變數名稱的 export let 來接收它。 https://gist.github.com/mhatvan/b67ceafb05d21c15b5782c068690d632 在現代 JavaScript 中,`export` 通常用作導出模塊的關鍵字和 `let` 聲明塊範圍變數,所以我覺得語法濫用現有關鍵字,但我習慣了它並且效果很好. ###開發速度 這與 Svelte 的開發體驗沒有直接關係,但您絕對應該知道,在財務支持方面,Svelte 無法(目前)與更大的和讚助的開源專案競爭,如 React、Angular、Vue.js 和其他專案,截至目前的貢獻者數量和受歡迎程度。 儘管如此,社區正在迅速發展,社區為 Svelte 建置的第三方專案列表也在不斷增加,這些專案可在 [Made with Svelte](https://madewithsvelte.com/) 上找到。開發 Svelte 相關工具的開發人員都是天才,您可以隨時在 [Discord](https://discord.com/invite/qa4pnmw) 頻道、[Twitter](https://twitter.com/sveltejs) 上尋求幫助) 或 [Reddit](https://reddit.com/r/sveltejs)。 Svelte 最近還加入了 TypeScript 支持,而且效果很好! 我喜歡 Svelte 的易用性、較小的包大小和開發人員體驗等因素,因此我可以接受較慢的開發速度作為權衡。如果您總是需要盡可能快地合併最新功能,那麼您可能需要查看其他可用的 JavaScript 框架。 ### 缺少可用的工作 大多數公司仍在尋找對三大前端框架有經驗的開發人員,但也有各種知名的 Svelte 早期採用者,如 IBM、Apple、Philips、GoDaddy、1Password 或紐約時報,僅舉幾例.您可以在 [Svelte 網站](https://svelte.dev/) 底部找到大量使用 Svelte 的公司。通常,採用新框架需要一段時間才能出現在公司的工作機會中。儘管如此,Svelte 學習起來很有趣,許多開發人員喜歡使用 Svelte,尤其是在他們自己的個人專案或小規模應用程式中。 ## 結論 如果對初學者友好的語法、較小的包大小輸出和 Svelte 的瘋狂性能對您來說是一個不錯的選擇,我建議您開始使用 [Svelte 教程](https://svelte.dev/tutorial/basics)。該教程非常詳細,您可以快速了解該框架的強大功能。 在 JavaScript 框架的世界裡,事情肯定會快速變化,我希望你和我一樣相信 Svelte 擁有所有的優勢和潛力,可以讓它成為新的 #1 JavaScript 前端框架! 您之前使用過 Svelte 嗎?你的經驗是什麼? 在評論中告訴我,我很想知道。 感謝閱讀,希望您喜歡! ## 有用的資源 - [Svelte 教程](https://svelte.dev/tutorial/basics) - [Svelte REPL](https://svelte.dev/repl) - [Rich Harris - 重新思考反應性](https://www.youtube.com/watch?v=AdNJ3fydeao) - [為什麼要苗條](https://github.com/feltcoop/why-svelte) - [為什麼 SvelteJS 可能是新 Web 開發人員的最佳框架](https://dev.to/bholmesdev/why-sveltejs-may-be-the-best-framework-for-new-web-devs-205i) - [為什麼我們從 React 轉向 Svelte](https://medium.com/better-programming/why-we-moved-from-react-to-svelte-f20afb1dc5d5) - [我喜歡 Svelte 的寫作風格](https://css-tricks.com/what-i-like-about-writing-styles-with-svelte/) - [我在 React 和 Svelte 中建立了完全相同的應用程式。這是差異。](https://medium.com/javascript-in-plain-english/i-created-the-exact-same-app-in-react-and-svelte-here-are-the-differences-c0bd2cc9b3f8) ## 正在尋找 Svelte 支持的伺服器端渲染解決方案? 在使用 [Sapper](https://sapper.svelte.dev/) 接觸框架後,我是一個忠實的粉絲,一有機會就嘗試推廣 Svelte 之道。 如果您要建立一個網站並正在尋找合適的工具,我發表了一篇關於我迄今為止使用 Sapper 的經驗的文章,供您在此處閱讀:[“為什麼我為我的網站選擇 SapperJS,以及我做了什麼”到目前為止,我已經了解了該框架”](https://markushatvan.com/blog/why-i-chose-sapperjs-for-my-website-and-what-ive-learned-about-the-framework-so-遠的)。

寫了多年 React 之後,改寫 Svelte 的心得與感想

原文出處:https://dev.to/mikenikles/why-i-moved-from-react-to-svelte-and-others-will-follow-210l # React 多年來一直是我的首選 2015 年 10 月 14 日,我主持了 [首屆 React 溫哥華聚會](https://www.meetup.com/ReactJS-Vancouver-Meetup/events/225362860/)。當時我在一年中的大部分時間裡都在使用 React,並希望將志同道合的開發人員聚集在一起。 那時的 React,我敢說,是 web 前端世界的革命性的。與 jQuery、Backbone.js 或 Angular 1.x 等替代方案相比,使用 React 進行開發感覺直觀、清新且富有成效。就個人而言,隔離建置塊(又名元件)的想法真的很吸引我,因為它自然會導致結構化、組織良好且更易於維護的程式碼庫。 在接下來的幾年裡,我一直密切關注 Angular 2.x+、Vue 等,但沒有一個是值得跳槽的選擇。 # 然後我了解了 Svelte 我第一次了解 Svelte 是在 2018 年年中,也就是 3.0 版發布前將近一年(見下文)。 “[計算機,為我建置一個應用程式。](https://www.youtube.com/watch?v=qqt6YxAZoOc)”[Rich Harris](https://twitter.com/Rich_Harris) 讓我著迷Svelte。 > 如果您不熟悉 Svelte ([https://svelte.dev/](https://svelte.dev/)),請存取網站並花 5 分鐘閱讀介紹。 閱讀了嗎?真的?優秀👍 看完影片後,我心中的主要問題是是否值得學習 Svelte 並開始將其用於新專案甚至現有專案。平心而論,Svelte 給我留下了深刻的印象,但仍然不足以讓我完全接受它。 # Svelte 3.x 2019 年 4 月 22 日 - [Svelte 3:重新思考反應性](https://svelte.dev/blog/svelte-3-rethinking-reactivity) 是我一直在等待的博文。 > 請花一些時間閱讀博文並[觀看影片](https://www.youtube.com/watch?v=AdNJ3fydeao) - 這是關於電子表格的,但我保證它很有趣😉 為什麼這是一件大事?首先,Svelte 團隊一直在談論版本 3,我想看看它的實際應用。另一方面,Svelte 及其承諾比我第一次聽說 React 時更讓我興奮。 那時我指導 Web 開發人員,並花了很多時間讓他們加快 React 的速度。為了開發 React 應用程式,需要學習、理解並在一定程度上掌握 JSX、CSS-in-JS、Redux、create-react-app、SSR 和其他概念。 > 對於 Svelte,這些都不是必需的。 ``` <script> let name = 'world'; </script> <style> h1 { color: blue; } </style> <h1>Hello {name}!</h1> ``` 夠簡單嗎?我同意。事實上,它非常簡單,我將它推薦給我的 Web 開發新手。 ## 很快,那段程式碼發生了什麼? `script` 標籤是元件邏輯所在的位置。 `style` 標籤定義了這個元件的 CSS - 這些都不會洩漏到元件之外,所以我們可以安全地使用 h1 並且它只適用於這個元件。它是真正的 CSS,而不是偽裝成 CSS 的 Javascript 對像或偽裝成 CSS 的字串文字。 底部是元件的 HTML。使用帶有 `{myVariable}` 的變數。與 React 的 JSX 相比,Svelte 允許您使用正確的 HTML 標籤,例如 `for`、`class` 而不是 `forHtml` 和 `className`。請參閱 React 文件中的“[屬性差異](https://reactjs.org/docs/dom-elements.html#differences-in-attributes)”以獲取所有非標準 HTML 屬性的列表。 # 讓我們重建 React 示例 為了讓您了解 Svelte 與 React 的對比,讓我們重新建置 [https://reactjs.org/](https://reactjs.org/) 上列出的內容。 ## 一個簡單的元件 請參閱上面的程式碼片段。 ## 一個有狀態的元件 [互動演示](https://svelte.dev/repl/6e9ef214ae774287b21f902d7e6f0e68?version=3.16.6) ``` <script> let seconds = 0; setInterval(() => seconds += 1, 1000); </script> Seconds: {seconds} ``` React:33行 Svelte:6 行 ## 一個應用程式 [互動演示](https://svelte.dev/repl/817d413fd6c344bf859f0dbf8063de2f?version=3.16.6) ``` <script> /* App.svelte */ import TodoList from './TodoList.svelte'; let items = []; let text = ''; const handleSubmit = () => { if (!text.length) { return } const newItem = { text, id: Date.now(), }; items = items.concat(newItem); } </script> <div> <h3>TODO</h3> <TodoList {items} /> <form on:submit|preventDefault={handleSubmit}> <label for="new-todo"> What needs to be done? </label> <input id="new-todo" bind:value={text} /> <button> Add #{items.length + 1} </button> </form> </div> ``` ``` <script> /* TodoList.svelte */ export let items = []; </script> <ul> {#each items as item} <li key={item.id}>{item.text}</li> {/each} </ul> ``` React:66行 Svelte:43 行 ## 使用外部插件的元件 [互動演示](https://svelte.dev/repl/28f4b2e36e4244b8b23cae3d584c4c88?version=3.16.6) ``` <script> const md = new window.remarkable.Remarkable(); let value = 'Hello, **world**!'; </script> <svelte:head> <script src="https://cdnjs.cloudflare.com/ajax/libs/remarkable/2.0.0/remarkable.min.js"></script> </svelte:head> <div className="MarkdownEditor"> <h3>Input</h3> <label htmlFor="markdown-content"> Enter some markdown </label> <textarea id="markdown-content" bind:value={value} /> <h3>Output</h3> <div className="content"> {@html md.render(value)} </div> </div> ``` React:42行 Svelte:24 行 > 更少的程式碼 = 更少的錯誤 > 更少的程式碼 = 更好的性能 = 更好的用戶體驗 > 更少的程式碼 = 更少的維護 = 更多的時間來開發功能 # 我還喜歡 Svelte 什麼? ## 反應性 另一個強大的功能是 [反應式聲明](https://svelte.dev/tutorial/reactive-declarations)。讓我們從一個例子開始: ``` <script> let count = 0; $: doubled = count * 2; function handleClick() { count += 1; } </script> <button on:click={handleClick}> Clicked {count} {count === 1 ? 'time' : 'times'} </button> <p>{count} doubled is {doubled}</p> ``` 每當你有依賴於其他變數的變數時,用 `$: myVariable = [引用其他變數的程式碼]` 聲明它們。以上,每當 count 發生變化時,doubled 都會自動重新計算,並且 UI 會更新以反映新值。 ## Stores 在需要跨元件共享狀態的情況下,Svelte 提供了存儲的概念。 [教程很好地解釋了 store](https://svelte.dev/tutorial/auto-subscriptions)。無需閱讀冗長的教程 - store 就這麼簡單。 ### Derived stores 通常,一家 store 依賴於其他 store。這就是 Svelte 提供 derived() 來組合 store 的地方。 [有關詳細訊息,請參閱教程](https://svelte.dev/tutorial/derived-stores)。 ## 作為邏輯塊等待 好吧,這是一個非常優雅的。讓我們從程式碼開始([交互式演示](https://svelte.dev/repl/b9fc662a253443dc901ff189ce1cdd4b?version=3.16.7)): ``` <script> let githubRepoInfoPromise; let repoName = 'mikenikles/ghost-v3-google-cloud-storage'; const loadRepoInfo = async () => { const response = await fetch(`https://api.github.com/repos/${repoName}`); if (response.status === 200) { return await response.json(); } else { throw new Error(response.statusText); } } const handleClick = () => { githubRepoInfoPromise = loadRepoInfo(); } </script> <input type="text" placeholder="user/repo" bind:value={repoName} /> <button on:click={handleClick}> load Github repo info </button> {#await githubRepoInfoPromise} <p>...loading</p> {:then apiResponse} <p>{apiResponse ? `${apiResponse.full_name} is written in ${apiResponse.language}` : ''}</p> {:catch error} <p style="color: red">{error.message}</p> {/await} ``` 看到 HTML 中的“#await”塊了嗎?在真實世界的應用程式中,您將有一個加載元件、一個錯誤元件和在這種情況下呈現 API 響應的實際元件。嘗試在文本框中輸入無效的 repo 名稱以觸發錯誤案例。 # “等等,那……呢?” ## 開源元件? 當我向某人介紹 Svelte 時,我得到的主要回應是“但是生態系統、元件、教程、工具等呢?” 是的,開源 Svelte 元件遠不及 React 元件多。話雖如此,您多久使用一個開源 React 元件並在沒有任何問題或不必要的開銷的情況下集成它?我認為我們 Javascript 社區中的許多人已經變得過於依賴 `npm install ...` 來拼湊一個 web 應用程式。通常建置自己的元件,尤其是在 Svelte 中,可以減少整體花費的時間。我沒有資料可以證明,這是基於我個人的經驗。 不過,與此相關的是,對於任何願意重用開源元件的人來說,Svelte 元件的列表越來越多。 ## 正在找工作? 機會很多,請參閱 [https://sveltejobs.dev/](https://sveltejobs.dev/)。 Apple 的欺詐工程團隊正在[尋找 Svelte 開發人員](https://sveltejobs.dev/jobs/apple-senior-front-end-developer)(截至 2019 年 12 月)。 還要記住,與申請需要 React、Vue、Angular 等的工作相比,競爭要小得多。 # 然後,有 Sapper 來部署 Svelte 應用程式 開發應用程式只是整個蛋糕的一小部分——應用程式還需要部署。為此,Svelte 團隊提供了 [Sapper](https://sapper.svelte.dev/)。這本身就是一篇完整的帖子,所以現在請查看網站了解詳細訊息。 # 結論 每天,新的 Web 開發人員開始他們的旅程,許多人遇到的第一件事就是不確定首先要學什麼。我說未來就是簡單、快速的開發時間,我想不出比這更簡單、更快的事情了: ``` <script> let name = 'world'; </script> <style> h1 { color: blue; } </style> <h1>Hello {name}!</h1> ``` 以上分享,希望對您有幫助

Svelte 程式範例:動手寫一個「蕃茄鐘工作法」小專案

原文出處:https://dev.to/vintharas/discovering-svelte-getting-started-with-svelte-writing-a-pomodoro-technique-app-2lph ## 開始使用 Svelte [開始使用 Svelte 的最簡單方法](https://svelte.dev/blog/the-easiest-way-to-get-started) 是: 1. 瀏覽 [svelte.dev 中的 Svelte 教程](https://svelte.dev/tutorial) 2. 在 [svelte.dev 中的 Svelte REPL](https://svelte.dev/repl) 中進行試玩 3. 使用 svelte 模板從頭開始建立應用程式 儘管我認為通讀教程對於學習 Svelte 的語法和可用的東西確實很有幫助,但我認為**學習某些東西的最佳方法是在盡可能接近它的環境中實際操作**會在現實世界中開發一個 Svelte 應用程式。 **[你需要自己努力解決問題才能真正學到東西](https://amzn.to/2soWN5m)**。 ## 建立一個新專案 我們使用 [degit](https://github.com/Rich-Harris/degit)(也是由 Svelte 的建立者 Rich Harris 編寫的專案腳手架工具)生成一個新專案。類型: ``` $ npx degit sveltejs/template il-pomodoro ``` 這將在 `il-pomodoro` 目錄中建立一個全新的 Svelte 專案。我們跳進去,安裝依賴項並執行開發伺服器: ``` # Jump in $ cd il-pomodoro # Install the dependencies $ npm install # Run the development server $ npm run dev ``` 現在我們在 localhost:5000 上打開瀏覽器,讓我們看看我們得到了什麼…… **塔達!測試成功!** ![](https://thepracticaldev.s3.amazonaws.com/i/zyr2vgqeub11k253xsdx.png) ## 設置你的編輯器 Svelte 是一個編譯器優先的框架,它編譯代表 Svelte 元件的 .svelte 文件來建置 Web 應用程式。我在教程中看到的那個特殊的 .svelte 擴展和非 Web 標準語法告訴我,我需要在我的編輯器中提供一些額外的支持來處理 Svelte。 Svelte 博客有一篇關於[如何設置編輯器以使用 Svelte](https://svelte.dev/blog/setting-up-your-editor) 的好文章。我通常使用 Vim 或 VSCode,所以讓我們設置這兩個編輯器以使用 Svelte。 ### 設置 VSCode 以使用 Svelte 對於 VSCode,有 [svelte-code](https://marketplace.visualstudio.com/items?itemName=JamesBirtles.svelte-vscode) 插件,它支持 `.svelte` 語法突出顯示、診斷、自動完成和 [更多](https://marketplace.visualstudio.com/items?itemName=JamesBirtles.svelte-vscode)。 ### 設置 Vim 以使用 Svelte 對於 Vim,[設置你的編輯器文章](https://svelte.dev/blog/setting-up-your-editor) 沒有提供很多支持。它基本上告訴您將 .svelte 文件的文件類型更改為 HTML。經過一番挖掘,我發現了一些插件,它們可以讓你在 Vim 中獲得更好的 Svelte 體驗,並達到 VSCode 的標準: * [vim-svelte](https://github.com/evanleck/vim-svelte) 為 .svelte 文件提供語法高亮和縮進 * [coc-svelte](https://github.com/coc-extensions/coc-svelte) 通過連接到 Svelte LSP [^2] 為 Svelte 開發提供類似 IDE 的高級支持。這是 [coc.nvim](https://github.com/neoclide/coc.nvim) 自動補全插件(恰好是我最喜歡的 vim 補全插件)的擴展。 好的,現在我們已經設置好了編輯器,讓我們仔細看看我們的新 Svelte 專案。 ## 檔案結構 我們在編輯器中打開 il-pomodoro 文件夾,我們會看到一堆文件和文件夾: * 一個 `src` 文件夾,其中包含 Svelte hello world 應用程式的源程式碼 * 一個 `public` 文件夾,在 Svelte 編譯器編譯和處理後將包含我們的 Web 應用程式 * `rollup.config.js`,其中包含我們的捆綁器 ([rollup](https://rollupjs.org/)) 的配置。 Rollup 負責使用 Svelte 處理我們的源程式碼文件,以生成可以在瀏覽器中執行的開發和生產包。 對於初學者來說非常有趣的部分發生在 `src` 文件夾中,所以我們接下來要看的地方。該文件夾僅包含兩個文件: * `App.svelte` 這是我們應用程式的根元件 * `main.js`,其中包含用於初始化我們的應用程式的引導程式碼 作為我們應用程式入口點的文件是“main.js”: ``` import App from './App.svelte'; const app = new App({ target: document.body, props: { name: 'world' } }); export default app; ``` 這會建立一個新的 Svelte `App` 元件,並將其附加到 `document.body`,並使用一個名為 `title` 的屬性,其值為 `world`。 讓我們看看 `App` 到底是什麼: ``` <script> export let name; </script> <main> <h1>Hello {name}!</h1> <p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p> </main> <style> main { text-align: center; padding: 1em; max-width: 240px; margin: 0 auto; } h1 { color: #ff3e00; text-transform: uppercase; font-size: 4em; font-weight: 100; } @media (min-width: 640px) { main { max-width: none; } } </style> ``` 我懂了!所以 Svelte 元件是一些可重用的 UI,它封裝了元件的標記 (HTML)、它的行為(`<script>` 標籤內的 JavaScript)及其外觀和感覺(`<style>` 標籤內的 CSS) .涼爽的!這就說得通了。 如果我們回到標記中,我們可以理解當我們將它指向 localhost:5000 時我們在瀏覽器中看到的內容: ``` <main> <h1>Hello {name}!</h1> <p>Visit the <a href="https://svelte.dev/tutorial">Svelte tutorial</a> to learn how to build Svelte apps.</p> </main> ``` prop `name` 在實例化時傳遞給元件,並保存在該 `name` 變數中: ``` <script> export let name; </script> ``` 然後傳播到元件的標記,並呈現在我們在瀏覽器中看到的“h1”標籤內。涼爽的!有點奇怪但熟悉的“export let name”語法必須是**Svelte 元件將其 API 定義為 props 的方式**。 ## 加入標題 讓我們開始修補一些簡單的東西,比如為應用程式的第一個視圖加入標題並將其綁定到一些資料。初始模板給了我如何做到這一點的提示。我只需要向我的元件加入一個新變數以包含該標題。因為我在原始模板中沒有用到 `name` 變數,所以我將替換它: ``` <script> export let title </script> ``` 並更新 `main.js` 以注入我的應用程式的標題: ``` import App from './App.svelte'; const app = new App({ target: document.body, props: { title: 'il Pomodoro' } }); export default app; ``` 再想一想,我真的不需要將該變數公開為道具。我們不希望此元件的用戶更改此標題,因此我們將其保留為元件內部的一部分。 讓我們重寫我們的 App 元件來執行此操作: ``` <script> let title = "il Pomodoro"; </script> ``` 最後,我將更新 HTML 模板以使用“title”而不是“name”: ``` <main> <h1>{title}</h1> </main> ``` **搞定了!** ![](https://www.barbarianmeetscoding.com/images/svelte-il-pomodoro.jpg) ## 任務列表 驚人的!讓我們繼續建立一個非常簡單的任務列表。由於這感覺像是一個完全獨立的責任,我們將把它放在它自己的元件中。 我建立了一個新文件“TaskList.svelte”來表示該新元件並加入了一些標記,以便在我從“App.svelte”中使用它時盡可能少地出錯: ``` <p>I'm a list of tasks</p> ``` 我將它加入到 `App.svelte`: ``` <script> let title = "il Pomodoro"; </script> <main> <h1>{title}</h1> <TaskList /> </main> <style> /* styles omitted for sake of clarity. They'd be here. */ </style> ``` 而且……沒用。嗯……我做錯了什麼…… VSCode 和瀏覽器都會警告我以下內容: ``` 'TaskList' is not defined. svelte(missing-declaration) ``` 這告訴我兩件事: 1. 我的 vim 設置沒有按預期工作,因為我在編輯器中沒有收到錯誤(稍後要解決的問題),並且 2.我好像忘記導入元件了! 當然!所以我將它加入到“App.svelte”元件中: ``` <script> let title = "il Pomodoro"; import TaskList from './TaskList.svelte'; </script> <main> <h1>{title}</h1> <TaskList /> </main> ``` 是的!** ![](https://www.barbarianmeetscoding.com/images/svelte-tasks-list-text.jpg) 現在讓我們加入一些任務。我今天的前 3 項任務是: ``` <script> const tasks = [ "plan some fun trip with Teo", "buy some flowers to my wife", "write an article about Svelte" ]; </script> ``` 現在我需要在列表中的螢幕上顯示這些內容。 Svelte 有一種特殊的方法來迭代模板內的列表:[{#each} 塊](https://svelte.dev/docs#each)。 它是這樣工作的: ``` <ul> {#each tasks as task} <li>{task}</li> {/each} </ul> ``` 因此,我們遍歷 tasks 列表中的每個 task 並將其放入列表項 li 元素中。我們還從列表中刪除了點,因為它們看起來很糟糕: ``` <style> ul { list-style: none; } </style> ``` 這就是我們得到的: ![](https://www.barbarianmeetscoding.com/images/svelte-tasks-list.jpg) **叮叮叮!** 番茄鐘結束了。得走了!我們將很快繼續使用更多 Svelte、交互式任務列表和番茄鐘。 > ### 尋找番茄鐘應用程式的源程式碼? > https://github.com/Vintharas/il-pomodoro-in-svelte > https://svelte.dev/repl/27164871e86d4ce1a9815489dc323500?version=3.16.7 ## 到目前為止的一些思考 驚人的!這是開始使用 Svelte 的快速方法。到目前為止,這是我的印象: * [svelte.dev](https://svelte.dev/docs) 真的很棒。 * [交互式教程](https://svelte.dev/tutorial) 有一個循序漸進的介紹,帶您了解 Svelte 的所有功能和重要概念。 * [Svelte playground](https://svelte.dev/repl) 真的很酷,它可以讓你修改 Svelte 建立多文件應用程式,保存它們並與你的朋友和同事分享。 * [開發文件非常好](https://svelte.dev/docs) 也非常全面並且有很多示例。將它們加入書籤並根據需要用作參考。 * **以上所有內容都提供了與 Svelte 的美妙初次接觸**,當您第一次進入一個新的生態系統時,您會非常感激。 * 開始新專案的方式有點奇怪。我已經習慣了所有具有 CLI 的流行框架,使用 `npx degit etc...` 來建立一個新專案有點令人困惑。但在前 5 秒的混亂之後,我只是執行命令並繼續我的生活。 * **我對文本編輯器支持的第一印象並不好**,例如,VSCode 沒有在 Svelte 模板內為我提供語句完成功能,而我希望它能工作(例如,允許我過濾“任務” `)。在我試用 Svelte 的短暫時間內,我沒有讓 Vim 設置正常工作。 * **使用 Svelte 本身就是一種非常好的體驗**。 * 初次接觸時,感覺 Web 標準非常友好,並且一切如您所願。最小驚奇原則非常適用於 Svelte。 * 我喜歡 Svelte 元件的平面結構,以及它在 HTML 標記、Javascript (`<script>`) 和 CSS (`<style>`) 中劃分元件的方式,這很有意義。樣板文件的數量幾乎可以忽略不計。 * 在標記中註入資料很簡單 * 使用 `export` 暴露 props 雖然不是標準的但很有意義並且很容易理解。 * 我想知道為什麼 Svelte 使用 `{#each tasks as task}` 而它可以使用 `{#for task of tasks}` 並減少學習 Svelte 的人的認知負荷。 (也就是需要學習更多的自定義語法) 這就是今天的全部內容!希望你喜歡這篇文章。保重並期待更多 Svelte 即將推出。 > 您是一位經驗豐富的 Svelte 用戶嗎?如果是這樣,請不要猶豫,告訴我我做事有多麼錯誤 :D 我很樂意聽取您的意見,我們都會因此變得更好。 ## 在 Vim 中修復 Svelte 經過一些故障排除後,我意識到按照 Svelte 博客中的建議,我之前使用自動命令設置 Svelte 以將 .svelte 文件的文件類型更新為 html: ``` augroup svelte au! BufNewFile,BufRead *.svelte set ft=html augroup END ``` 這意味著沒有應用 coc-vim 和 svelte 語法文件,因為它們需要 svelte 的文件類型。刪除自動命令後,一切都像在 Visual Studio Code 中一樣好用。哇哇! [^1]:查看 [這個超級古老的番茄工作法應用程式](https://www.barbarianmeetscoding.com/projects/ilpomodoro/) 我在開始進行 Web 開發的那一天使用 Knockout.js 編寫的。 [^2]: LSP 代表語言伺服器協議。 (來自維基百科)它是一個開放的、基於 JSON-RPC 的協議,用於文本編輯器或 IDE 和提供編程語言特定功能的伺服器之間。該協議的目標是允許獨立於任何給定的編輯器或 IDE 實現和分發編程語言支持。

15 個 JavaScript 日常操作的實用、簡潔寫法

這裡有多種簡短而強大的 JavaScript 技巧,可以最大限度地提高生產力 ⚡️ 並最大限度地減少痛苦 🩸。 讓我們深入研究看看🤘 原文出處:https://dev.to/ironcladdev/15-killer-js-techniques-youve-probably-never-heard-of-1lgp ### 唯一陣列 過濾掉陣列中的重複值。 ``` const arr = ["a", "b", "c", "d", "d", "c", "e"] const uniqueArray = Array.from(new Set(arr)); console.log(uniqueArray); // ['a', 'b', 'c', 'd', 'e'] ``` ### 唯一的物件陣列 `Set` 物件不允許您過濾掉重複的物件,因為每個物件都是不同的。 `JSON.stringify` 在這裡幫我們解決了這個問題。 ``` const arr = [{ key: 'value' }, { key2: 'value2' }, { key: 'value' }, { key3: 'value3' }]; const uniqueObjects = Array.from( new Set( arr.map(JSON.stringify) ) ).map(JSON.parse) console.log(uniqueObjects); ``` 在 [此評論](https://dev.to/jonrandy/comment/24ojn) 中查看更有效但稍長的方法。 ### 陣列迭代器索引 通過 `.map` 和 `.forEach` javascript 迭代函數,您可以獲得每個項目的索引。 ``` const arr = ['a', 'b', 'c']; const letterPositions = arr.map( (char, index) => `${char} is at index ${index}` ) ``` ### 按字元數拆分字串 我們可以使用 `.match` 正則表達式函數將字串拆分為 `n` 個字符。 ``` const str = "asdfghjklmnopq"; const splitPairs = str.match(/.{1,2}/g); console.log(splitPairs); // ['as', 'df', 'gh', 'jk', 'lm', 'no', 'pq'] ``` ### 用不同的字元拆分字串 另一個使用 .match 的正則表達式 hack 允許您將像“aabbc”這樣的字串拆分為陣列“[”aa”,“bb”,“c”]`。 ``` const str = "abbcccdeefghhiijklll"; const splitChars = str.match(/(.)\1*/g); console.log(splitChars); // ['a', 'bb', 'ccc', 'd', 'ee', 'f', 'g', 'hh', 'ii', 'j', 'k', 'lll'] ``` ### 遍歷物件 `Object.entries` 允許我們將 JSON 物件轉換為鍵值對陣列,從而使我們能夠使用循環或陣列迭代器對其進行迭代。 ``` const obj = { "key1": "value1", "key2": "value2", "key3": "value3" }; const iteratedObject = Object.entries(obj) .map(([key, value]) => `${key} = ${value}`); console.log(iteratedObject); // ['key1 = value1', 'key2 = value2', 'key3 = value3'] ``` ### 鍵值陣列到物件 您可以使用“Object.fromEntries”將“Object.entryified”鍵值對陣列轉換回物件 ``` const entryified = [ ["key1", "value1"], ["key2", "value2"], ["key3", "value3"] ]; const originalObject = Object.fromEntries(entryified); console.log(originalObject); // { key1: 'value1', ... } ``` ### 發生次數計數 您可能想計算一個專案在陣列中出現的次數。我們可以使用帶有迭代器的 .filter 函數來完成此操作。 ``` const occurrences = ["a", "b", "c", "c", "d", "a", "a", "e", "f", "e", "f", "g", "f", "f", "f"]; // creating a unique array to avoid counting the same char more than once const unique = Array.from(new Set(occurrences)); const occurrenceCount = Object.fromEntries( unique.map(char => { const occurrenceCount = occurrences.filter(c => c === char).length; return [char, occurrenceCount] }) ) console.log(occurrenceCount); // { a: 3, b: 1, c: 2, ... } ``` 在 [此評論](https://dev.to/jonrandy/comment/24ojn) 中查看可靠的單行程式碼以執行此操作! ### 替換回調 `.replace` 函數並不限制您只能用固定字串替換。您可以將回調傳遞給它並使用匹配的子字串。 ``` const string = "a dog went to dig and dug a doggone large hole"; const replacedString = string.replace(/d.g/g, str => str + "gy") console.log(replacedString); // a doggy went to diggy and duggy a doggygone large hole ``` ### 條件串接 你們中的許多人都熟悉在 JS 中遇到未定義的錯誤,條件連結可以防止很多這種情況的發生。 > **可選連結** (`?.`) 運算符存取物件的屬性或呼叫函數。如果使用此運算符存取的對像或呼叫的函數未定義或為空,則表達式短路併計算為未定義,而不是拋出錯誤。 ``` const obj = { "a": "aaaaaaa", "b": null }; console.log(obj.b.d); // throws an error console.log(obj.b?.d); // returns undefined ``` ### 限定一個數字 通常,您可能需要將數字限制在特定範圍內。每次需要時都用三元運算符來做是一件很痛苦的事情。函數要乾淨得多。 ``` const constrain = (num, min, max) => { if(num < min) return min; else if(num > max) return max; else return num; } constrain(5, 1, 3) // 3 constrain(2, 1, 5) // 2 constrain(0, -100, 100) // 0 ``` 一個更好的方法是像這樣使用 `Math.min` 和 `Math.max`: ``` const constrain = (num, min, max) => Math.min(Math.max(num, min), max) ``` ### 索引陣列的前後 `.at` 函數允許您使用正數和負數從頭到尾對陣列進行索引。 ``` const arr = [1, 2, 3, 4, 5]; arr.at(0) // 1 arr.at(1) // 2 arr.at(-1) // 5 arr.at(-2) // 4 ``` ### 按字母順序排序 按字母順序對字串陣列進行排序 ``` const words = ["javascript", "typescript", "python", "ruby", "swift", "go", "clojure"]; const sorted = words.sort((a, b) => a.localeCompare(b)); console.log(sorted); // ['clojure', 'go', 'javascript', 'python', 'ruby', 'swift', 'typescript'] ``` 💡 **提示**:您可以通過將 `a.localeCompare(b)` 切換為 `b.localeCompare(a)` 來切換升序和降序 ### 按 Truthy/Falsy 值排序 您可以按真值/假值對陣列進行排序,將具有真值的值放在最前面,然後是假值。 ``` const users = [ { "name": "john", "subscribed": false }, { "name": "jane", "subscribed": true }, { "name": "jean", "subscribed": false }, { "name": "george", "subscribed": true }, { "name": "jelly", "subscribed": true }, { "name": "john", "subscribed": false } ]; const subscribedUsersFirst = users.sort((a, b) => Number(b.subscribed) - Number(a.subscribed)) ``` `Number(false)` 等於 0,`Number(true)` 等於 1。這就是我們如何通過排序函數傳遞它。 ### 四捨五入到 `n` 位 您可以使用 .toFixed 將小數四捨五入為 n 位。請注意,`.toFixed` 將數字轉換為字串,因此我們必須將其重新解析為數字。 ``` console.log(Math.PI); // 3.141592653589793 console.log(Number(Math.PI.toFixed(2))) ``` --- 感謝閱讀✨!

22 個很好用的 CSS 小訣竅&特殊小技巧

**🚨🚨注:**本文分享的所有tips、tricks都是GitHub repository[【css tips tricks】](https://github.com/devsyedmohsin/css-tips-tricks)的一部分。覺得有用的話請查看資源庫並給它一個star🌟 原文出處:https://dev.to/devsyedmohsin/22-useful-css-tips-and-tricks-every-developer-should-know-13c6 ## 1. Docs Layout 僅用兩行 CSS 建立響應式文件樣式的佈局。 ``` .parent{ display: grid; grid-template-columns: minmax(150px, 25%) 1fr; } ``` ![佈局](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ojs8nvly2ugashxwqif8.png) ## 2.自定義游標 查看 github 存儲庫 [css 提示技巧](https://github.com/devsyedmohsin/css-tips-tricks) 以了解更多訊息。 ``` html{ cursor:url('no.png'), auto; } ``` ![帶有自定義光標的圖像](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ba8kist57vp6l9spw8w2.gif) ## 3. 用圖片填充文本 ``` h1{ background-image: url('images/flower.jpg'); background-clip: text; color: transparent; background-color: white; } ``` ![Air Max](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0a7my28raxr80upv77k1.png) **注意:** 在使用此技術時始終指定 `background-color`,因為這將用作後備值,以防圖像因某種原因無法加載。 ## 4. 給文本加入描邊 使用 text-stroke 屬性使文本更易讀和可見,它會向文本加入筆劃或輪廓。 ``` /* 🎨 Apply a 5px wide crimson text stroke to h1 elements */ h1 { -webkit-text-stroke: 5px crimson; text-stroke: 5px crimson; } ``` ![NETLIFY](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h9xcwsh18vxqw1uaj5h3.png) ## 5.暫停 Pseudo Class 使用 `:paused` 選擇器在暫停狀態下設置媒體元素的樣式 同樣 `:paused` 我們也有 `:playing`。 ``` /* 📢 currently, only supported in Safari */ video:paused { opacity: 0.6; } ``` ![河上的棕櫚樹](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dq1za9uri1a37kqyh1y1.gif) ## 6.強調文字 使用 text-emphasis 屬性將強調標記應用於文本元素。您可以指定任何字串,包括表情符號作為其值。 ``` h1 { text-emphasis: "⏰"; } ``` ![時間是良藥](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6l1oifo8erkkblsk7ilt.png) ## 7.樣式首字下沉 避免不必要的 `<span>`,而是使用偽元素來為您的內容設置樣式,就像 `first-letter` 偽元素一樣,我們也有 `first-line` 偽元素。 ``` h1::first-letter{ font-size: 2rem; color:#ff8A00; } ``` ![Gitpod.io](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a1jtvgnx1y1xqf0sd9b7.png) ## 8.變數的回退值 ``` /* 🎨 crimson color will be applied as var(--black) is not defined */ :root { --orange: orange; --coral: coral; } h1 { color: var(--black, crimson); } ``` ![深紅色文字“說話,你很重要”](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r2477mnixnrwtwn5mqun.png) ## 9. 改變書寫模式 您可以使用書寫模式屬性來指定文本在您的網站上的佈局方式,即垂直或水平。 ``` <h1>Cakes & Bakes</h1> ``` ``` /* 💡 specifies the text layout direction to sideways-lr */ h1 { writing-mode: sideways-lr; } ``` ![文本開始於](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ozqs02sh7edl70cd609a.png) ## 10.彩虹動畫 為元素建立連續循環的彩色動畫以吸引用戶注意力。閱讀 [css 提示技巧](https://github.com/devsyedmohsin/css-tips-tricks#rainbow-animation) 存儲庫以了解何時使用“prefer-reduced-motion”媒體功能 ``` button{ animation: rainbow-animation 200ms linear infinite; } @keyframes rainbow-animation { to{ filter: hue-rotate(0deg); } from{ filter: hue-rotate(360deg); } } ``` ![立即購買按鈕不斷改變顏色](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60jgrr09vgsckx9h2irl.gif) ## 11.掌握Web開發 訂閱我們的 [YouTube 頻道](https://www.youtube.com/@nisarhassan12),讓您的網絡開發技能更上一層樓。 [最近的視頻系列](https://www.youtube.com/watch?v=1nchVfpMGSg&list=PLwJBGAxcH7GzdavgKlCACbESzr-40lw3L) 之一介紹了建立以下開源[投資組合模板](https://github.com/nisarhassan12 /投資組合模板)。 ![伊蒙](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bxid827qfq1ybx2tl3q7.gif) ## 12. 懸停時縮放 ``` /* 📷 Define the height and width of the image container & hide overflow */ .img-container { height: 250px; width: 250px; overflow: hidden; } /* 🖼️ Make the image inside the container fill the container */ .img-container img { height: 100%; width: 100%; object-fit: cover; transition: transform 200m ease-in; } img:hover{ transform: scale(1.2); } ``` ![躺在灰色瓷磚上的深紅色購物袋](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cxy8ymu937e0kf14wwbc.gif) ## 13.屬性選擇器 使用屬性選擇器根據屬性選擇 HTML 元素。 ``` <a href="">HTML</a> <a>CSS</a> <a href="">JavaScript</a> ``` ``` /* 🔗 targets all a elements that have a href attribute */ a[href] { color: crimson; } ``` ![HTML CSS JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1sq2rhs58a01ayfqzexk.png) ## 14. 裁剪元素 使用 `clip-path` 屬性建立有趣的視覺效果,例如將元素剪裁成三角形或六邊形等自定義形狀。 ``` div { height: 150px; width: 150px; background-color: crimson; clip-path: polygon(50% 0%, 0% 100%, 100% 100%); } ``` ![三角形](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u9eqxif34ndhq33xvlpb.png) ## 15.檢測屬性支持 使用 CSS `@support 規則` 直接在您的 CSS 中檢測對 CSS 特性的支持。查看 [css 提示技巧](https://github.com/devsyedmohsin/css-tips-tricks#check-if-property-is-supported) 存儲庫以了解有關功能查詢的更多訊息。 ``` @supports (accent-color: #74992e) { /* code that will run if the property is supported */ blockquote { color: crimson; } } ``` ![永遠不要食言。(Hazrat Ali A.S)](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8ekr2fmhl4ori47xqgyf.png) ## 16. CSS 嵌套 CSS 工作組一直在研究如何向 CSS 加入嵌套。通過嵌套,您將能夠編寫更直觀、更有條理和更高效的 CSS。 ``` <header class="header"> <p class="text">Lorem ipsum, dolor</p> </header> ``` ``` /* 🎉 You can try CSS nesting now in Safari Technology Preview*/ .header{ background-color: salmon; .text{ font-size: 18px; } } ``` ## 17.箝制函數 使用 `clamp()` 函數實現響應式和流暢的排版。 ``` /* Syntax: clamp(minimum, preferred, maximum) */ h1{ font-size: clamp(2.25rem,6vw,4rem); } ``` ![gif 字體大小根據屏幕大小改變](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/upaf9jdlfapezzmufyaa.gif) ## 18. 樣式化可選字段 你可以使用 `:optional` 偽類來設置表單字段的樣式,例如 input、select 和 textarea,這些字段沒有 required 屬性。 ``` /* Selects all optional form fields on the page */ *:optional{ background-color: green; } ``` ## 19. 字間距屬性 使用 `word-spacing` 屬性指定單詞之間的空格長度。 ``` p { word-spacing: 1.245rem; } ``` ## 20. 建立漸變陰影 這就是您如何建立漸變陰影以獲得獨特的用戶體驗。 ``` :root{ --gradient: linear-gradient(to bottom right, crimson, coral); } div { height: 200px; width: 200px; background-image: var(--gradient); border-radius: 1rem; position: relative; } div::after { content: ""; position: absolute; inset: 0; background-image: var(--gradient); border-radius: inherit; filter: blur(25px) brightness(1.5); transform: translateY(15%) scale(0.95); z-index: -1; } ``` ![帶有漸變陰影的框](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7korhhx7zaj350nfzmyb.png) ## 21. 改變標題位置 使用 `caption-side` 屬性將表格標題(表格標題)放置在表格的指定一側。 ![從上到下更改表格標題側](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7t44rugi8gx3ksndq560.gif) ## 22. 建立文本列 使用列屬性為文本元素製作漂亮的列佈局。 ``` /* 🏛️ divide the content of the "p" element into 3 columns */ p{ column-count: 3; column-gap: 4.45rem; column-rule: 2px dotted crimson; } ``` ![css 提示和技巧詩](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y1ryft9s27y56el3ljx4.png) --- 以上分享,希望對您有幫助!

給開發者的 15 份好用 Cheatsheets 分享

隨著程式設計技術的快速發展,我們必須學習很多新東西。有些語言和框架非常複雜,您可能記不住所有的語法或方法。備忘單就是您易於存取的筆記了。 每當有人發現任何有幫助或有價值的事情時,我們都會做筆記。但是,您不需要對在書籍、研討會或文章中看到的每個細節都做筆記。 為了幫助您學習,我編寫了這份頂級備忘單列表。 - 原文出處:https://dev.to/ishratumar/15-must-have-cheatsheets-for-developers-1n92 --- ## HTML, CSS, and JavaScript Cheatsheet 您可以在此處找到 HTML、CSS 和 JavaScript 程式碼範例。每個例子都有一個解釋。像這樣的備忘單是我的最愛之一。 連結:https://htmlcheatsheet.com/js/ ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/msaqyef5m5nkk3op6oq8.jpg) ## JavaScript Cheatsheet 這是對初學者的 JavaScript 的完整、快速的介紹。值得看一下。 連結:https://quickref.me/javascript ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bbhfqsoinyj3142ix5z7.jpg) ## React.js Cheatsheet React 是最流行的 JavaScript 函式庫。對於 React 愛好者來說,這是一個簡單但有用的備忘單。一定要將它加入書籤,以便快速參考。 連結:https://devhints.io/react/ ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1i30duid59mry623p8ee.jpg) ## Cheatography 沒有比這更好的資源了。它有超過 5,000 個備忘單、修訂輔助工具和快速參考!每個人都可以在這裡得到他們需要的一切,而不僅僅是軟體工程師。在這裡,您可以找到有關 Web 開發、商業、遊戲、健康、數位行銷等的備忘單。 連結:https://cheatography.com/ ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9oqaebo7kjce31dc3klp.jpg) ## Java Cheat Sheets 此處簡要列出了教科書中使用最多的 Java 語言特性和 API。這是一個很好的快速參考。 連結:https://introcs.cs.princeton.edu/java/11cheatsheet/ ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0hfa25tmgbd263f0biwk.jpg) ## OverAPI Over API 是一個了不起的資源。對於大多數編程語言,您可以在此處找到備忘單。 連結:https://overapi.com/ ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dv049973s0b5jgk5jroy.jpg) ## Devhints 這裡有一些範例、連結、片段等,可讓您簡要了解該語言的基礎知識。在一頁上,您會找到詳細的說明。值得研究。 連結:https://devhints.io/ ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u3l5nr66wiwvruv1iyga.jpg) ## Gitsheet Git 是開發人員應具備的最重要的技能。這是一個非常簡單的 git 命令備忘單。如果您可以存取此 Gitsheet,則無需記住所有命令。 連結:https://gitsheet.wtf/ ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gcf2ah61erkjkzov13nw.jpg) ## Vue.js cheatsheet 此備忘單包含 Vue.js 的詳細程式碼片段和解釋。它包括與屬性、DOM、資料、事件、生命週期、API 等相關的片段。如果您正在尋找 Vue.js 的快速參考,請檢查一下。 連結:https://marozed.com/vue-cheatsheet/ ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/c9uq2dcd2i3wxfhjef8b.jpg) ## HTML5 Canvas Cheat Sheet 可在此處找到 HTML5 Canvas 的程式碼示例,包括其元素、2D 上下文、線條樣式、顏色、陰影等。在此處了解有關 HTML 畫布的所有訊息。 連結:https://simon.html5.org/dump/html5-canvas-cheat-sheet.html ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2a8tz7vnxr0ec5huaylb.jpg) ## Web 開發人員的 SEO 備忘單 這個網站是關於 SEO(搜尋引擎優化)的。在最有效的搜尋引擎優化技巧中,這是最有用的快速參考之一。 Web 開發人員和軟體工程師也受益於輕鬆存取 SEO 技術標準。 連結:https://moz.com/learn/seo ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/izmc3x46eyc1rdvy90tf.jpg) ## Easing functions 通過使用緩動函數,您可以調整動畫的速度以建立各種效果,例如彈跳、減速、放大等。有關詳細訊息,請參閱此 Microsoft 文件。 此外,參數隨時間變化的速率由緩動函數指定。現實世界中的物體幾乎從不以一致的速度移動,也很少突然開始和結束。使用此頁面,您可以選擇理想的緩動函數。 連結:https://easings.net/en# ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/58cd8pj9bj0m44qd1cth.jpg) ## CSS3 動畫 這個網站有一些驚人的動畫效果,你可以在你的下一個專案中使用。 連結:http://www.justinaguilar.com/animations/# ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/75v2qv333wzgw8qo5019.jpg) ## CSS 網格 CSS 網格可能有點挑戰性。因此,很難記住它的所有屬性。您可以將此備忘單加入到您的書籤中以供快速參考。 連結:https://grid.malven.co/ ![圖片說明](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m2zj6k2wrtb0pszd1u7n.jpg) --- 以上,簡單分享,希望對您有幫助!

JavaScript 系列八:第4課 ── 行事曆應用程式

## 課程目標 - 能夠寫出行事曆應用程式 ## 課程內容 現在新推出的大部份 javascript 套件,都會提供 native(原生)、React、Vue 三種版本,方便使用 舉例來說,這款行事曆套件,就有多種版本 https://fullcalendar.io/ 也有易安裝的 CDN 版本 https://fullcalendar.io/docs/initialize-globals --- 所謂的 React、Vue 或是任何框架版本,其實就只是把套件,根據框架規格,封裝成元件而已 (元件的觀念,之後會教,先別擔心) 套件會大量跟 DOM 互動,框架也會跟 DOM 互動,兩者容易衝突,使用上通常會 bug 一大堆 所以官方會推出套件版本,改掉一些底層寫法,方便框架用戶使用 如果沒有,那就由開發者自己小心管理,通常也沒太大問題 就是把初始化相關放在 `mounted` 裡面,然後狀態更新時,找方法與套件狀態同步,就這樣而已 --- 這一課來寫行事曆應用程式 關鍵字 `calendar app ui` ## 課後作業 請使用 https://replit.com/ 來寫作業 這次作業的規格如下: - 這種程式應該要讓人註冊登入使用,需要後端配合,但我們簡化吧:免登入、把資料存在 local storage 就好 - 有一個「新增活動」按鈕,點擊可以輸入「活動名稱」、選擇「活動日期」與「活動時間」 - 不用做成「開始、結束」兩個時間點,就做成開始時間就好 - 日期時間的 UI,請使用 https://github.com/xdan/datetimepicker - 上述功能,可以做成 modal 視窗(輸入欄位放在視窗內),也可以直接把輸入欄位都放在畫面上 - 使用 FullCalendar 呈現行事曆,將活動顯示在對應日期 - 點擊行事曆內的活動,可以刪除活動。請使用 javascript 內建的 `confirm` 函式,確認「是否刪除此筆活動?」後刪除 - 請「不要」用官方 Vue 版本,請用 CDN 版本,學著自己在框架內導入套件 做出以上功能,你就完成這次的課程目標了!

JavaScript 系列七:第1課 ── 認識 Vue 基本環境與 render state

## 課程目標 - 能夠運行 Vue 基本環境 - 能夠 render state ## 課程內容 身為工程師,要習慣到處翻閱各種技術文件 這次的課程,我不會手把手帶領,細談所有觀念 我會一次提供一個官網連結。請你一邊閱讀,一邊把其中的範例貼到 jsfiddle 跑跑看 我會額外提供簡單介紹&關鍵字,然後補充一些注意事項 官網文件內容是英文,如果對英文沒把握,就去翻中文官網 https://cn.vuejs.org/guide/introduction.html 但是,長遠來說,還是要逐漸提升自己的英語閱讀能力才行 --- 先學基本的安裝&運行 - https://vuejs.org/guide/quick-start.html 這系列課程,我們用最簡單的 CDN 環境來跑就好了,先只學 CDN 那一段就好 --- 接著來學 Vue 最基本觀念 - https://vuejs.org/guide/essentials/application.html - https://vuejs.org/guide/essentials/template-syntax.html 內容很多,大部份看不懂沒關係,稍微有個印象就好 如同我在前言所說,同一件事有很多種花俏寫法,你根本不用全部學會 這一課我們只要學會如何 render state 就好了 ``` <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <div id="app"> {{ user.name }} 喜歡吃 {{ fruits[0].name }} 以及 {{ fruits[1].name }} </div> <script> const { createApp } = Vue createApp({ data() { return { user: { name: "John Doe" }, fruits: [ { name: "Apple", }, { name: "Banana", }, ] } } }).mount('#app') </script> ``` 上面這段範例,在 `data()` 函式將 application state 準備好 然後只要將一段作為 UI 的 html 寫好,我們稱之為模板(template) 接著 Vue 就會把 state 放進 template 裡面,把結果給 render 出來 貼到 jsfiddle 跑跑看吧,你會發現非常簡單、好理解 ## 課後作業 這系列課程,我們要模仿 Google Keep 製作一個應用程式 請先把玩一下 Google Keep https://keep.google.com/ 作業使用 jsfiddle 來寫 --- 這一課先簡單呈現 UI 就好 請使用以下這段 code 作為 application state ``` data() { return { notes: [ { title: "春節行程安排", content: "吃飽睡,睡飽吃", color: "red", }, { title: "工作待辦事項", content: "詢問各家廠商報價", color: "green", }, { title: "運動健身計畫", content: "每天早上六點去健身", color: "blue", }, ] } } ``` 使用以下這段 code 作為 template ``` <div id="app"> <div class="note"> <h3 class="title"> <!-- 請顯示第一個項目的標題 --> </h3> <p class="content"> <!-- 請顯示第一個項目的內容 --> </p> </div> <div class="note"> <h3 class="title"> <!-- 請顯示第二個項目的標題 --> </h3> <p class="content"> <!-- 請顯示第二個項目的內容 --> </p> </div> <div class="note"> <h3 class="title"> <!-- 請顯示第三個項目的標題 --> </h3> <p class="content"> <!-- 請顯示第三個項目的內容 --> </p> </div> </div> ``` - 陣列內容就只有三筆資料,就只要顯示這三筆資料就好 - 在 application state 裡面的陣列,直接用 `索引` 來取出值就好,這一課先不用寫 for 迴圈 - color 這一課還不會用到,可以先忽略沒關係 - 請在 `<style>` 加上一些樣式,讓整個頁面漂亮一點 - 每則記事可以單純的放進網頁就好,不用像 Google Keep 那樣花式的排版(那種叫瀑布流排版,很難寫) 做出以上功能,你就完成這次的課程目標了!

軟體開發者推薦使用:50 個好用的 CLI 指令工具

作為開發人員,我們在終端機上花費了大量時間。有很多有用的 CLI 工具,它們可以讓您在命令行中的生活更輕鬆、更快速,而且通常更有趣。 這篇文章概述了 50 個必備的好用 CLI 工具。 原文出處:https://dev.to/lissy93/cli-tools-you-cant-live-without-57f6 --- ## 工具 ### [`thefuck`](https://github.com/nvbn/thefuck) - 自動更正錯誤輸入的命令 > `thefuck` 是您一旦嘗試過就離不開的實用程式之一。每當您輸入錯誤的命令並出現錯誤時,只需執行 `fuck`,它就會自動更正它。使用向上/向下選擇一個更正,或者只執行 `fuck --yeah` 立即執行最有可能的。 ![他媽的示例用法](https://i.ibb.co/J55hWKX/thefuck.gif) --- ### [`zoxide`](https://github.com/ajeetdsouza/zoxide) - 輕鬆導航 _(更好的 cd)_ > `z` 讓您可以跳轉到任何目錄,而無需記住或指定其完整路徑。它會記住您存取過的目錄,因此您可以快速跳轉——您甚至不需要鍵入完整的文件夾名稱。它還具有互動式選項,使用“fzf”,因此您可以即時過濾目錄結果 ![zoxide-example-usage](https://i.ibb.co/6Z960jq/zoxide.gif) --- ### [`tldr`](https://github.com/tldr-pages/tldr) - 社區維護的文件 _(更好的 `man`)_ > `tldr` 是社區維護的手冊頁的巨大集合。與傳統的手冊頁不同,它們進行了總結,包含有用的用法範例,並且配色良好,便於閱讀 ![tldr-example-usage](https://i.ibb.co/jTW9knx/tlfr.gif) --- ### [`scc`](https://github.com/boyter/scc) - 計算程式碼行數_(更好的`cloc`)_ > `scc` 為您提供了針對特定目錄以每種語言編寫的程式碼行數的細分。它還顯示了一些有趣的統計資料,例如估計的開發成本和復雜性訊息。它的速度非常快,非常準確,並且支持多種語言 ![scc-example-usage](https://i.ibb.co/NygHWXt/scc.png) --- ### [`exa`](https://github.com/ogham/exa) - 列出文件 _(更好的 `ls`)_ > `exa` 是基於 Rust 的現代替代 `ls` 命令,用於列出文件。它可以顯示文件類型圖標、顏色、文件/文件夾訊息,並有多種輸出格式——樹、網格或列表 ![exa-example-usage](https://i.ibb.co/cTs0wQ5/exa.png) --- ### [`duf`](https://github.com/muesli/duf) - 硬碟使用量 _(更好的 `df`)_ > `duf` 非常適合顯示有關已安裝硬碟的訊息和檢查可用空間。它產生清晰多彩的輸出,並包括用於排序和自定義結果的選項。 ![duf-示例用法](https://i.ibb.co/sP59DKd/duf.png) --- ### [`aria2`](https://github.com/aria2/aria2) - 下載實用程式 _(更好的 `wget`)_ > `aria2` 是一種輕量級、多協議、用於 HTTP/HTTPS、FTP、SFTP、BitTorrent 和 Metalink 的恢復下載實用程序,支持通過 RPC 接口進行控制。它的[功能豐富](https://aria2.github.io/manual/en/html/README.html)令人難以置信,並且有大量的[選項](https://aria2.github.io/manual/en/ html/aria2c.html)。還有 [ziahamza/webui-aria2](https://github.com/ziahamza/webui-aria2) - 一個不錯的網路介面搭配。 ![aria2c-example-usage](https://i.ibb.co/pJkkX6x/aria2c.png) --- ### [`bat`](https://github.com/sharkdp/bat) - 讀取文件_(更好的`cat`)_ > `bat` 是 `cat` 的複製品,但具有語法高亮顯示和 git 集成。它是用 Rust 編寫的,性能非常好,並且有多個用於自定義輸出和主題的選項。支持自動管道和文件連接 ![bat-example-usage](https://i.ibb.co/VND3Y9s/bat.png) --- ### [`diff-so-fancy`](https://github.com/so-fancy/diff-so-fancy) - 文件比較_(更好的`diff`)_ > `diff-so-fancy` 為比較字串、文件、目錄和 git 更改提供了更好看的差異。更改突出顯示使發現更改變得更加容易,並且您可以自定義輸出佈局和顏色 ![diff-so-fancy-example-usage](https://i.ibb.co/RGKLhQk/diff-so-fancy.png) --- ### [`entr`](https://github.com/eradman/entr) - 觀察變化 > `entr` 允許您在文件更改時執行任意命令。您可以傳遞一個文件、目錄、符號連結或正則表達式來指定它應該監視哪些文件。它對於自動重建專案、響應日誌、自動化測試等非常有用。與類似專案不同,它使用 kqueue(2) 或 inotify(7) 來避免輪詢,並提高性能 ![entr-example-usage](https://i.ibb.co/HHKQx2H/entr.png) --- ### [`exiftool`](https://github.com/exiftool/exiftool) - 讀取+寫入元資料 > ExifTool 是一個方便的實用程序,用於讀取、寫入、剝離和建立各種文件類型的元訊息。再次分享照片時不要不小心洩露您的位置! ![exiftool-example-usage](https://i.ibb.co/Gv5PN6v/exiftool.png) --- ### [`fdupes`](https://github.com/jbruchon/jdupes) - 重複文件查找器 > `jdupes` 用於辨識和/或刪除指定目錄中的重複文件。當您有兩個或更多相同的文件時,它對於釋放硬碟空間很有用 ![fdupes-example-usage](https://i.ibb.co/jhSY2Nn/fdupes.png) --- ### [`fzf`](https://github.com/junegunn/fzf) - 模糊文件查找器_(更好的`find`)_ > `fzf` 是一個非常強大且易於使用的模糊文件查找器和過濾工具。它允許您跨文件搜尋字串或模式。 fzf 也有可用於大多數 shell 和 IDE 的[插件](https://github.com/junegunn/fzf/wiki/Related-projects),用於在搜尋時顯示即時結果。這篇由 Alexey Samoshkin 撰寫的 [文章](https://www.freecodecamp.org/news/fzf-a-command-line-fuzzy-finder-missing-demo-a7de312403ff/) 重點介紹了它的一些用例。 ![fzf-示例用法](https://i.ibb.co/LNcwjWm/fzf.gif) --- ### [`hyperfine`](https://github.com/sharkdp/hyperfine) - 命令基準測試 > `hyperfine` 可以輕鬆準確地對任意命令或腳本進行基準測試和比較。它負責預熱執行、清除緩存以獲得準確的結果並防止來自其他程序的干擾。它還可以將結果導出為原始資料並生成圖表。 ![hyperfine-example-usage](https://i.ibb.co/tKNR5gr/hyperfine.png) --- ### [`just`](https://github.com/casey/just) - 現代命令執行器_(更好的`make`)_ > `just` 與 `make` 類似,但增加了一些不錯的功能。它讓您可以將專案命令分組到副本中,這些副本可以輕鬆列出和執行。支持別名、位置參數、不同的 shell、dot env 集成、字串插入以及幾乎所有您可能需要的東西 --- ### [`jq`](https://github.com/stedolan/jq) - JSON 處理器 > `jq` 類似於 `sed`,但對於 JSON - 您可以使用它輕鬆地切片、過濾、映射和轉換結構化資料。它可用於編寫複雜的查詢以提取或操作 JSON 資料。還有一個 [jq playground](https://jqplay.org/),您可以用來試用,或通過即時回饋制定查詢 --- ### [`most`](https://www.jedsoft.org/most/) - 多窗口滾動尋呼機_(更好的 less)_ > `most` 是一個尋呼機,用於讀取長文件或命令輸出。 `most` 支持多窗口並且可以選擇不換行 --- ### [`procs`](https://github.com/dalance/procs) - 進程查看器_(更好的 ps)_ > `procs` 是一個易於導航的流程查看器,它具有彩色突出顯示,使流程的排序和搜尋變得容易,具有樹視圖和實時更新 ![procs-example-usage](https://i.ibb.co/y6qhgDX/procs-demo.gif) --- ### [`rip`](https://github.com/nivekuil/rip) - 刪除工具_(更好的 rm)_ > `rip` 是一種安全、符合人體工程學且高性能的刪除工具。它讓您直觀地刪除文件和目錄,並輕鬆恢復已刪除的文件 ![rip-example-usage](https://i.ibb.co/10DTvT2/rip.gif) --- ### [`ripgrep`](https://github.com/BurntSushi/ripgrep) - 在文件中搜尋 _(更好的 `grep`)_ > `ripgrep` 是一種面向行的搜尋工具,可遞歸地在當前目錄中搜尋正則表達式模式。它可以忽略 .gitignore 的內容並跳過二進製文件。它能夠在壓縮檔案中搜尋,或只搜尋特定的擴展名,並使用各種編碼方法理解文件 ![ripgrep-example-usage](https://i.ibb.co/qkMgQm9/ripgrep.png) --- ### [`rsync`](https://rsync.samba.org/) - 快速、增量文件傳輸 > `rsync` 讓您可以在本地複制大文件,或將大文件複製到遠程主機或外部驅動器或從遠程主機或外部驅動器複製。它可用於保持多個位置的文件同步,非常適合建立、更新和恢復備份 --- ### [`sd`](https://github.com/chmln/sd) - 查找並替換_(更好的`sed`)_ > `sd` 是一種簡單、快速且直觀的查找和替換工具,基於字串文字。它可以在文件、整個目錄或任何管道文本上執行 ![sd-示例用法](https://i.ibb.co/G9CfcGS/sd.png) --- ### [`tre`](https://github.com/dduan/tre) - 目錄層次結構_(更好的`tree`)_ > `tre` 輸出當前目錄或指定目錄的樹形文件列表,並帶有顏色。使用“-e”選項執行時,它會為每個專案編號,並建立一個臨時別名,您可以使用該別名快速跳轉到該位置 ![tre-example-usage](https://i.ibb.co/CmMrZLB/tre.png) --- ### [`xsel`](https://github.com/kfish/xsel) - 存取剪貼板 > `xsel` 讓您通過命令行讀取和寫入 X 選擇剪貼板。它對於將命令輸出通過管道傳輸到剪貼板或將復制的資料傳輸到命令中很有用 --- ## CLI 監控和性能應用程式 ### [`bandwhich`](https://github.com/imsnif/bandwhich) - 頻寬利用率監視器 > 即時顯示頻寬使用情況、連接訊息、傳出主機和 DNS 查詢 ![bandwhich-example-usage](https://i.ibb.co/8jHHBD3/Screenshot-from-2023-01-18-22-45-32.png) --- ### [`ctop`](https://github.com/bcicen/ctop) - 容器指標和監控 > 類似於 `top`,但用於監控正在執行的(Docker 和 runC)容器的資源使用情況。它顯示實時 CPU、內存和網絡帶寬以及每個容器的名稱、狀態和 ID。還有一個內置的日誌查看器和管理(停止、啟動、執行等)容器的選項 ![ctop-example-usage](https://i.ibb.co/xGjyzZ2/ctop.gif) --- ### [`bpytop`](https://github.com/aristocratos/bpytop) - 資源監控_(更好的`htop`)_ > `bpytop` 是一種快速、交互式、可視化的資源監視器。它顯示了最熱門的執行進程、最近的 CPU、內存、磁盤和網絡歷史記錄。您可以從界面中導航、排序和搜尋——還支持自定義顏色主題 ![bpytop-example-usage](https://i.ibb.co/nj9jrhr/bpytop.gif) --- ### [`glances`](https://github.com/nicolargo/glances) - 資源監視器 + 網絡和 API > `glances` 是另一個資源監視器,但具有不同的功能集。它包括一個完全響應的 Web 視圖、一個 REST API 和歷史監控。它易於擴展,並且可以與其他服務集成 ![掃視示例用法](https://i.ibb.co/6g65Qy4/glances.gif) --- ### [`gping`](https://github.com/orf/gping) - 交互式 ping 工具 _(更好的 `ping`)_ > `gping` 可以在多個主機上執行 ping 測試,同時以實時圖形顯示結果。當與 --cmd 標誌一起使用時,它還可以用於監視執行時間 ![gping 示例用法](https://i.ibb.co/CvG6xt0/gping.gif) --- ### [`dua-cli`](https://github.com/Byron/dua-cli) - 磁盤使用分析器和監視器 _(更好的 `du`)_ > `dua-cli` 讓您以交互方式查看每個已安裝驅動器的已用和可用磁盤空間,並輕鬆釋放存儲空間 ![dua-cli-usage-example](https://i.ibb.co/x3NbDLR/dua.gif) --- ### [`speedtest-cli`](https://github.com/sivel/speedtest-cli) - 命令行速度測試實用程序 > `speedtest-cli` 只是執行網路速度測試,通過 speedtest.net - 但直接從終端 :) ![speedtest-cli-example-usage](https://i.ibb.co/25QCbdF/speedtest-cli.gif) --- ### [`dog`](https://github.com/ogham/dog) - DNS 查找客戶端_(更好的`dig`)_ > `dog` 是一個易於使用的 DNS 查找客戶端,支持 DoT 和 DoH,漂亮的彩色輸出和發出 JSON 的選項 ![dog-example-usage](https://i.ibb.co/48n617Q/dog.png) --- ## CLI 生產力應用程式 > 上網衝浪、播放音樂、查看電子郵件、管理日曆、閱讀新聞等等,無需離開終端! ### [`browsh`](https://github.com/browsh-org/browsh) - CLI 網路瀏覽器 > `browsh` 是一個完全交互的、實時的、現代的基於文本的瀏覽器,呈現給 TTY 和瀏覽器。它同時支持鼠標和鍵盤導航,並且對於純基於終端的應用程式來說功能豐富得令人吃驚。它還緩解了困擾現代瀏覽器的電池耗盡問題,並且通過對 MoSH 的支持,由於帶寬減少,您可以體驗更快的加載時間 ![browsh-example-usage](https://i.ibb.co/S7nLFX5/browsh.gif) --- ### [`books`](https://github.com/jarun/books) - 書籤管理器 > `buku` 是一個基於終端的書籤管理器,具有大量的配置、存儲和使用選項。還有一個可選的 [web UI](https://github.com/jarun/buku/tree/master/bukuserver#screenshots) 和 [瀏覽器插件](https://github.com/samhh/bukubrow-webext#installation ), 用於在終端外存取您的書籤 ![buku-example-usage](https://i.ibb.co/CWQsf1x/buku.png) --- ### [`cmus`](https://github.com/cmus/cmus) - 音樂瀏覽器/播放器 > `cmus` 是終端音樂播放器,由鍵盤快捷鍵控制。它支持廣泛的音頻格式和編解碼器,並允許將曲目組織到播放列表中並應用播放設置 ![cmus-example-usage](https://i.ibb.co/dP6b3bd/cmus.png) --- ### [`cointop`](https://github.com/cointop-sh/cointop) - 跟踪加密價格 > `cointop` 顯示當前的加密貨幣價格,並跟踪您的投資組合的價格歷史。支持價格提醒、歷史圖表、貨幣換算、模糊搜尋等。您可以通過網絡 [cointop.sh](https://cointop.sh/) 或執行 `ssh cointop.sh` 來嘗試演示 ![cointop-example-usage](https://i.ibb.co/JBf9y4y/cointop.png) --- ### [`ddgr`](https://github.com/jarun/ddgr) - 從終端搜尋網頁 > `ddgr` 類似於 [googler](https://github.com/jarun/googler),但適用於 DuckDuckGo。它快速、乾淨、簡單,支持即時回答、搜尋完成、搜尋 bangs 和高級搜尋。它默認尊重您的隱私,也有 HTTPS 代理支持,並與 Tor 一起工作 ![dggr-example-usage](https://i.ibb.co/S0H21QH/dggr.png) --- ### [`micro`](https://github.com/zyedidia/micro) - 程式碼編輯器_(更好的`nano`)_ > `micro` 是一款易於使用、快速且可擴展的程式碼編輯器,支持鼠標。由於它被打包成一個二進製文件,安裝就像`curl https://getmic.ro | 安裝一樣簡單。慶典` --- ### [`khal`](https://github.com/pimutils/khal) - 日曆客戶端 > `khal` 是一個終端日曆應用程式,它顯示即將發生的事件、月份和議程視圖。您可以將它與任何 CalDAV 日曆同步,並直接加入、編輯和刪除事件 ![khal-example-usage](https://i.ibb.co/hLCdjZW/khal.png) --- ### [`mutt`](https://gitlab.com/muttmua/mutt) - 電子郵件客戶端 > `mut` 是一個經典的、基於終端的郵件客戶端,用於發送、閱讀和管理電子郵件。它支持所有主流電子郵件協議和郵箱格式,允許附件、密件抄送/抄送、線程、郵件列表和傳遞狀態通知 ![mutt-example-usage](https://i.ibb.co/zVVsG3s/mutt.webp) --- ### [`newsboat`](https://github.com/newsboat/newsboat) - RSS / ATOM 新聞閱讀器 > `newsboat` 是一個 RSS 提要閱讀器和聚合器,用於直接從終端閱讀新聞、博客和後續更新 ![newsboat-example-usage](https://i.ibb.co/fvT4YzD/newsboat.png) --- ### [`rclone`](https://github.com/rclone/rclone) - 管理雲存儲 > `rclone` 是一個方便的實用程序,用於將文件和文件夾同步到各種雲存儲提供商。它可以直接從命令行呼叫,也可以輕鬆集成到腳本中以替代繁重的桌面同步應用程式 --- ### [`taskwarrior`](https://github.com/GothenburgBitFactory/taskwarrior) - Todo + 任務管理 > `task` 是一個 CLI 任務管理/待辦事項應用程式。它既簡單又不引人注目,但也非常強大和可擴展,內置高級組織和查詢功能。還有很多(700+!)額外的[插件](https://taskwarrior.org/tools/) 用於擴展它的功能和與第三方服務的集成 ![任務戰士示例用法](https://i.ibb.co/7k6M37g/taskwarrior.jpg) --- ### [`tuir`](https://gitlab.com/ajak/tuir) - Reddit 的終端用戶界面 > `tuir` 是一個很好的選擇,如果你想看起來像在工作,同時實際瀏覽 Reddit!它具有直觀的鍵綁定、自定義主題,還可以呈現圖像和多媒體內容。還有 [haxor](https://github.com/donnemartin/haxor-news) 用於黑客新聞 ![tuir-example-usage](https://i.ibb.co/vzSw7s5/tuir.png) --- ## CLI 開發套件 ### [`httpie`](https://github.com/httpie/httpie) - HTTP/API測試測試客戶端 > `httpie` 是一個 HTTP 客戶端,用於測試、除錯和使用 API。它支持您所期望的一切——HTTPS、代理、身份驗證、自定義標頭、持久會話、JSON 解析。具有表達語法和彩色輸出的用法很簡單。與其他 HTTP 客戶端(Postman、Hopscotch、Insomnia 等)一樣,HTTPie 也包含一個 Web UI ![httpie-示例用法](https://i.ibb.co/Wk5S19g/httpie.png) --- ### [`lazydocker`](https://github.com/jesseduffield/lazydocker) - 完整的 Docker 管理應用程式 > `lazydocker` 是一個 Docker 管理應用程式,可讓您查看所有容器和圖像、管理它們的狀態、讀取日誌、檢查資源使用情況、重新啟動/重建、分析層、修剪未使用的容器、圖像和卷等等。它使您無需記住、鍵入和連結多個 Docker 命令。 ![lazy-docker-example-usage](https://i.ibb.co/MD8MWNH/lazydocker.png) --- ### [`lazygit`](https://github.com/jesseduffield/lazygit) - 完整的 Git 管理應用程式 > `lazygit` 是一個可視化的 git 客戶端,在命令行上。輕鬆加入、提交和推送文件、解決衝突、比較差異、管理日誌以及執行壓縮和倒帶等複雜操作。一切都有鍵綁定,顏色,而且很容易配置和擴展 ![lazy-git-example-usage](https://i.ibb.co/KLF3C6s/lazygit.png) --- ### [`kdash`](https://github.com/kdash-rs/kdash/) - Kubernetes 儀表板應用程式 > `kdash` 是一個一體化的 Kubernetes 管理工具。查看節點指標、觀察資源、流容器日誌、分析上下文和管理節點、pod 和命名空間 --- ### [`gdp-dashboard`](https://github.com/cyrus-and/gdb-dashboard) - 可視化 GDP 除錯器 > `gdp-dashboard` 向 GNU 除錯器加入了一個可視元素,用於除錯 C 和 C++ 程序。輕鬆分析內存、單步執行斷點和查看寄存器 ![gdp-dashboard-example-usage](https://i.ibb.co/2g2hVLh/gdp-dashboard.png) --- ## CLI 外部服務 ### [`ngrok`](https://ngrok.com/) - 共享本地主機的反向代理 > `ngrok` 安全* 將您的本地主機暴露在唯一 URL 後面的網路上。這使您可以與遠程同事實時共享您的工作。使用[非常簡單](https://notes.aliciasykes.com/p/RUi22QSyWe),但它也有很多高級功能,例如身份驗證、webhooks、防火牆、流量檢查、自定義/通配符域等等 ![ngrok-示例用法](https://i.ibb.co/4WPZNGx/ngrok.png) --- ### [`tmate`](https://tmate.io/) - 通過網路共享終端會話 > `tmate` 讓您立即與世界其他地方的人分享實時終端會話。跨系統工作,支持存取控制/授權,可自託管,具備Tmux的所有特性 --- ### [`asciinema`](https://asciinema.org/) - 錄製+分享終端會話 > `asciinema` 對於輕鬆記錄、共享和嵌入終端會話非常有用。非常適合展示您建置的內容,或展示教程的命令行步驟。與屏幕錄製視頻不同,用戶可以復制粘貼內容、動態更改主題和控製播放 --- ### [`navi`](https://github.com/denisidoro/navi) - 交互式備忘單 > `navi` 允許您瀏覽備忘單並執行命令。參數的建議值動態顯示在列表中。減少輸入,減少錯誤,讓自己不必記住數千條命令。它集成了 [tldr](https://github.com/tldr-pages/tldr) 和 [cheat.sh](https://github.com/chubin/cheat.sh) 以獲取內容,但您也可以導入其他備忘單,甚至編寫自己的備忘單 --- ### [`transfer.sh`](https://github.com/dutchcoders/transfer.sh/) - 快速文件共享 > `transfer` 使上傳和共享文件變得非常簡單,直接從命令行即可。它是免費的,支持加密,為您提供唯一的 URL,也可以自行託管。 > 我寫了一個 Bash 輔助函數來讓使用更容易一些,你可以[在這裡找到它](https://github.com/Lissy93/dotfiles/blob/master/utils/transfer.sh) 或嘗試一下通過執行`bash <(curl -L -s https://alicia.url.lol/transfer)` ![transfer-sh-example-usage](https://i.ibb.co/cCqDb1k/transfer-sh.png) --- ### [`surge`](https://surge.sh/) - 在幾秒鐘內部署一個站點 > `surge` 是一個免費的靜態託管服務提供商,您可以通過一個命令直接從終端部署到它,只需在您的 `dist` 目錄中執行 `surge`!它支持自定義域、自動 SSL 憑證、pushState 支持、跨域資源支持——而且是免費的! ![surge-sh-example-usage](https://i.ibb.co/NynprxZ/surge-sh.png) --- ### [`wttr.in`](https://github.com/chubin/wttr.in) - 查看天氣 > `wttr.in` 是一項以命令行中易於理解的格式顯示天氣的服務。只需執行“curl wttr.in”或“curl wttr.in/London”來嘗試一下。有 URL 參數來自定義返回的資料以及格式 ![wrrt-in-example-usage](https://i.ibb.co/J2JWnYT/Screenshot-from-2023-01-18-21-10-54.png) --- ## CLI 樂趣 ### [`cowsay`](https://en.wikipedia.org/wiki/Cowsay) - 讓 ASCII 牛說出你的訊息 > `cowsay` 是一個可配置的會說話的奶牛。它基於 Tony Monroe 的[原創](https://github.com/tnalpgge/rank-amateur-cowsay) ![cowsay-example-usage](https://i.ibb.co/TRqW3jD/cowsay.png) --- ### [`figlet`](http://www.figlet.org/) - 將文本輸出為大型 ASCII 藝術文本 > `figlet` 將文本輸出為 ASCII 藝術 ![figlet-example-usage](https://i.ibb.co/fk4T7D0/figlet.png) --- ### [`lolcat`](https://github.com/busyloop/lolcat) - 使控制台輸出彩虹色 > `lolcat` 使任何傳遞給它的文本變成彩虹色 ![lolcat-example-usage](https://i.ibb.co/nfp9Ycx/lolcat.png) --- ### [`neofetch`](https://github.com/dylanaraps/neofetch) - 顯示系統資料和 ditstro 訊息 > `neofetch` 打印發行版和系統訊息(這樣你就可以靈活地在 r/unixporn 上使用 Arch btw) ![neofetch-example-usage](https://i.ibb.co/x1PHpFC/Screenshot-from-2023-01-18-22-44-28.png) 例如,我使用 `cowsay`、`figlet`、`lolcat` 和 `neofetch` 來建立一個自定義的基於時間的 MOTD,在用戶首次登錄時顯示給他們。它以他們的名字問候他們,顯示伺服器訊息和時間、日期、天氣和 IP。 [這裡是源程式碼](https://github.com/Lissy93/dotfiles/blob/master/utils/welcome-banner.sh)。 ![歡迎](https://i.ibb.co/cTg0jyn/Screenshot-from-2023-01-18-22-59-28.png) --- ## 安裝和管理 我們大多數人都有一套核心的 CLI 應用程式和我們所依賴的實用程序。設置一台新機器並單獨安裝每個程序很快就會讓人厭煩。因此,安裝和更新終端應用程式的任務非常適合自動化。 [此處](https://github.com/Lissy93/dotfiles/tree/master/scripts/installs) 是我編寫的一些示例腳本,可以輕鬆將其放入您的點文件或獨立執行以確保您永遠不會錯過一個應用程式。 對於 MacOS 用戶,最簡單的方法是使用 [Homebrew](https://brew.sh/)。只需建立一個 Brewfile(使用 `touch ~/.Brewfile`),然後列出您的每個應用程式,然後執行 `brew bundle`。您可以通過將其放入 Git 存儲庫來備份您的包列表。這是一個示例,讓您入門:https://github.com/Lissy93/Brewfile 在 Linux 上,您通常希望使用本機包管理器(例如 `pacman`、`apt`)。例如,[這裡有一個腳本](https://github.com/Lissy93/dotfiles/blob/master/scripts/installs/arch-pacman.sh) 用於在 Arch Linux 系統上安裝上述應用程式 Linux 上的桌面應用程式可以通過 Flatpak 以類似的方式進行管理。同樣,[這是一個示例腳本](https://github.com/Lissy93/dotfiles/blob/master/scripts/installs/flatpak.sh) :) --- ## 結論 ...就是這樣 - 一個方便的 CLI 應用程式列表,以及一種在您的系統中安裝和保持它們最新的方法。 希望其中一些對你們中的一些人有用:)

JavaScript 系列四:第4課 ── jQuery 套件

## 課程目標 認識並且能使用 jQuery 套件 ## 課程內容 這一課要教的東西比較有爭議 jQuery 是 2006 - 2015 年代,前端網頁開發的王者 當時的瀏覽器廠商眾多,網頁規格 API 支援方式不同、不完整(尤其是 IE 一堆奇怪的 API) 當時的前端工程師,非常痛苦,要為了 IE 多改很多寫法 加上當時很多瀏覽器沒有支援 `.querySelector` `.querySelectorAll` 這些 Selector API 所以 jQuery 的出現,強大的選擇器語法,以及眾多方便的功能,大幅降低了前端開發的成本 不過,時至今日,jQuery 的大部份功能,都已在瀏覽器 JavaScript 語法中原生支援了 再加上開發大型應用程式,DOM 的管理一旦複雜起來,就會直接使用 React 或者 Vue 這種框架來管理 DOM,不會再手動去操作 DOM (前端框架會處理完 DOM 互動的部份。此時如果再手動操作 DOM,那程式碼就會一團混亂) 也就是說,小型專案,「不需要」用 jQuery;大型專案,「不可以」用 jQuery 除此之外,jQuery 套件本身檔案不小,引入此套件會影響網頁載入速度,影響 UX,同時會影響搜尋引擎 SEO 排名 --- 因為上述種種原因,在今天,前端工程師普遍鄙視 jQuery,避之惟恐不及 我個人的建議是:團隊在開發複雜的前端應用時,的確不要再用 jQuery 了! 但是,當只是做小網站,接小案子賺錢,或者做個人的業餘專案(side project),只是希望快速做完某些功能時,jQuery 還是非常好用! 原因有兩個 第一,jQuery 選擇器寫起來很短,可以少打很多字,開發很快速 第二,jQuery 外掛生態系存在已久,很多強大的 UI 元件會用到 jQuery,適合的話,實在沒道理全面放棄不用 而且,並不是所有網站,都需要直接導入 React 跟 Vue 這種大型框架!沒必要! 除此之外,維護一大堆現有的程式碼,難免已經用到 jQuery,還是能看懂 API 比較好 所以,還是稍微教大家一些 jQuery 的用法。至於什麼場合要使用,你就自行判斷吧 --- 官網 https://jquery.com/ API 用法 https://api.jquery.com/ CDN 連結 https://releases.jquery.com/ 請自行逛一逛,大概知道 jQuery 有哪些 API 就好,不用花太多時間學習 jQuery 你應該會發現,一大堆功能,你自己就寫得出來,而且寫起來也不複雜,例如 `.hide()` `.show()`,你之前的作業就寫過,根本不需要用 jQuery 剩下的一大堆功能,目前看不懂沒關係、覺得自己做不出來沒關係,未來的課程會教你 --- 簡單地說,jQuery 選擇器就是使用金錢符號來呼叫函示 `$()` 其實是 `jQuery()` 的簡寫而已 ``` <h1 class="title"> Hide me </h1> <p class="para"> Hide me </p> <p class="para"> Hide me </p> <p class="para"> Hide me </p> ``` ``` document.querySelector('.title').style.display = 'none'; for (var p of document.querySelectorAll('.para')) { p.style.display = 'none'; } ``` 像這樣的程式,隱藏了畫面上多個元素 使用 jQuery 的寫法會變成 ``` $('.title').hide(); $('.para').hide(); ``` 很多人覺得,jQuery 只剩一些少打字的功能,卻讓網頁多載入整個 jQuery 套件,很沒意義、不值得 我倒是覺得,還是滿方便的。快速開發時,少打很多字。而且 jQuery 可以自動處理多個元素,可以少寫 for 迴圈 當然了,上面的程式碼,跟下面這段是完全一樣的 ``` jQuery('.title').hide(); jQuery('.para').hide(); ``` jQuery 基本上就這樣而已,你喜歡嗎? 實務上,使用時,如果翻文件,還是不知怎麼寫,就去搜尋引擎找關鍵字 `jquery 改變顏色` `jquery change color` 之類的 別忘了,軟體工程師在工作時,會花很多時間在翻文件、上網到處看文章、搜尋範例程式碼,所以要習慣這件事 --- 坊間很多課程,會在一開始就教 jQuery。這跟直接教前端框架的問題一樣:學生的基本功,因此變得很差 但是本課程已讓你知道最基本的原生 DOM 寫法,所以你在用 jQuery 時,會知道背後發生什麼事,也知道刪掉 jQuery 的話,要怎麼用原生語法改寫 所以,我認為在本課程的安排下,jQuery 並不會耽誤你的學習旅程 喜歡 jQuery 的話,就把 API 網頁,多逛一逛,工作上想用的話,就大方使用吧! ## 課後作業 請使用 https://jsfiddle.net 這次的作業要交兩份 請建立兩份 jsfiddle,並使用以下 html ``` <h1 class="title"> Make me green </h1> <p class="para"> Make me red </p> <p class="para"> Me red too </p> <p class="para"> Also me </p> ``` 在第一份,不使用 jQuery,把 h1 文字變為綠色,p 文字變為紅色 在第二份,請使用 jQuery,把 h1 文字變為綠色,p 文字變為紅色 寫完之後,你自行比較一下,網頁多加一個肥大的套件,但是可以少打這些字,你覺得值得嗎? 這是一個主觀問題,你就根據情況決定你的答案吧! 做出以上功能,你就完成這次的課程目標了!

JavaScript 系列四:第1課 ── autosize 套件

## 課程目標 認識並且能使用 autosize 套件 ## 課程內容 這次的套件是 https://github.com/jackmoore/autosize 文件與 demo 在 https://www.jacklmoore.com/autosize/ 這是一個讓 `<textarea>` 的 UX(User Experience 使用者體驗)瞬間升級的好用套件 ``` // from a NodeList autosize(document.querySelectorAll('textarea')); // from a single Node autosize(document.querySelector('textarea')); ``` 使用起來非常簡單,把 DOM 元素找到,當成參數傳給 autosize 函式,就可以了 在設計各種第三方套件給別人的時候,通常都會設計成這樣,很簡單、易用吧 程式的使用方法,我們叫 API(Application Programming Interface,應用程式介面) 實務上,我們會跟同事說:「去查一下這個套件的 API」,也就是去看一下這套件的使用方法。可以理解成「產品規格」 --- 在上網搜尋套件的時候,第一個要先看這個專案的星星數量,至少要有幾百顆以上吧 如果是太冷門的套件,代表可能不夠成熟、文件不完整、潛在 bug 會很多 第二個要看的是最近更新日期,也就是 last commit 的時間,至少兩年內有更新過吧 太久沒更新的專案,可能有點過時,會跟最新的瀏覽器或者其他工具有衝突 不過,如果只是用在網站上的小小地方,真的出問題,再換掉的成本也不大,那就先導入也沒關係 --- 要使用第三方套件,除了直接下載然後使用 `<script>` 引入之外,還有一個常用的懶人方法 就是搜尋 `套件名稱 CDN`,直接找現成的 CDN 連結來用 CDN 全名 Content Distribution Network,內容傳遞網路。這是大型企業讓資源在全球加速載入用的 看不懂沒關係,反正搜尋 `套件名稱 CDN`,通常會有現成 `<script>` 可用 搜尋 `autosize cdn` 看看搜尋結果,就會知道了 (要注意這是一個懶人方法,工作上直接這樣用,網站可能會載入的有點慢) ## 課後作業 請使用 https://jsfiddle.net 假設你正在開發一個留言功能 有暱稱欄位、留言欄位、以及一個送出按鈕 留言的區塊,`textarea` 預設只有三行的高度 使用者在輸入時,輸入越多行,輸入區塊會自動變高,而不會出現捲軸 做出以上功能,你就完成這次的課程目標了!

給自學 JavaScript 的初學者:7 個可以學習基本觀念的 Github 專案

使用這些 github repo 成為更好的前端開發人員。 原文出處:https://dev.to/hy_piyush/7-github-repositories-that-every-front-end-developer-must-know-300l ## Clean Code JavaScript 一些能幫助您程式碼更簡潔的開發觀念。 GitHub 連結:https://github.com/ryanmcdermott/clean-code-javascript ## JavaScript Algorithms and Data Structure 用 JavaScript 實作的演算法和資料結構,有解釋和進一步閱讀的連結 包含許多流行演算法和資料結構的 JavaScript 範例。 每個演算法和資料結構都有自己單獨的 README,帶有相關的解釋和進一步閱讀的連結。 GitHub 連結:https://github.com/trekhleb/javascript-algorithms ## You Don’t Know JavaScript 這是一個關於 JavaScript 的系列叢書。這是一系列深入探討 JavaScript 語言核心機制的書籍。 GitHub 連結:https://github.com/getify/You-Dont-Know-JS ## NodeJS Best Practice 這個存儲庫是對 Node.js 最佳實踐的總結和管理。這將幫助許多開發人員獲得有關 NodeJS 後端開發的進階知識。 GitHub 連結:https://github.com/goldbergyoni/nodebestpractices ## Frontend Checklist 適用於現代網站和專業開發人員的完美前端清單。它基於前端開發人員多年的經驗,並加入了一些其他開源清單。 GitHub 連結:https://github.com/thedaviddias/Front-End-Checklist ## Free For Dev 對 DevOps 和基礎設施開發,具有免費方案的 SaaS、PaaS 和 IaaS 產品列表。 不過,此列表的內容只對基礎架構開發人員(系統管理員、DevOps 從業者等)有用。 GitHub 連結:https://github.com/jixserver/free-for-dev ## DSA in JavaScript 解釋和實作的資料結構和演算法。 GitHub 連結:https://github.com/amejiarosario/dsa.js-data-structures-algorithms-javascript

CSS 基本觀念:rem 跟 em 差在哪?何時該用哪個?有何注意事項?

## 簡介 CSS 是任何網站設計的重要組成部分,但理解其中一些細微差別觀念可能不容易。其中最重要的觀念之一是 rem 和 em 之間的區別,以及為什麼/何時應該使用它們。 原文出處:https://dev.to/refine/rem-vs-em-everything-you-need-to-know-5342 --- ## 預備知識 本文希望讀者對 CSS 有紮實的掌握。雖然你不必成為 CSS 大神,但如果基本的 CSS 術語你都清楚,那會好讀很多。 ## CSS 中的 em 和 rem 單位 在尋找在 CSS 中設定長度的方法時,有太多方法了。 CSS 中指定長度的所有單位都屬於兩類。 絕對長度:顧名思義,就是絕對的;它們是固定的,不會對任何事物做出反應。這意味著無論發生什麼,它們的大小都是一樣的。絕對長度包括 cm、mm、in、px、pts 和 pc。 相對長度:是指定相對於另一個單位的長度的單位,即,它們根據其他指定單位或元素做出響應。包括 %、vmax、vmin、vh、vw、ch、ex,以及我們將要討論的單位 em 和 rem。 如果您想了解更多關於這些單位的訊息,可以現在先去查一查。現在讓我們看看這兩個單位。 ## 什麼是 CSS em 就像我上面說的,CSS 中的 em 單位是用於調整網頁元素大小的相對測量單位,主要是字體大小。因為是相對於父元素的,所以1em等於父元素中設置的font-size。 這意味著如果您將父 div 中的字體大小設置為 20px,並將子 div 中的字體大小設置為 2em,則子 div 中的字體大小將等於 40px。這是一個例子。 首先,讓我們編寫 HTML ``` <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="parent"> I'm parent div set to 20px <div class="child"> I'm the child div set to 2em, i.e 40px. </div> </div> </body> </html> ``` Next, the CSS. ``` .parent{ font-size: 20px; } .child{ font-size: 2em; } p { font-size: 1.5em; } ``` 那會給我們這個。 ![](https://refine.ams3.cdn.digitaloceanspaces.com/blog/2022-12-21-em-vs-rem/em-vs-rem-1.png) em 單位很有用,因為它允許您根據先前宣告的元素的字體大小調整頁面上元素的大小,這有助於建立一致的視覺層次結構。這對於建立易於視障用戶閱讀的可存取網站非常有用。 需要注意的是,如果不指定父元素的值,則以瀏覽器的預設值作為父元素。 ``` p { font-size: 1.5em; } ``` 在此範例中,字體大小屬性設置為 1.5em,這意味著如果沒有直接父元素,`<p>` 元素中的文本大小將是瀏覽器預設字體大小大小的 1.5 倍。 由於大多數瀏覽器根據螢幕大小縮放其預設字體大小,這使您可以建立靈活且響應迅速的佈局,以適應不同的螢幕和字體大小。 使用適當的 CSS 屬性,em 單位也可用於設置其他元素的大小,例如邊距、填充和邊框。 ## 什麼是 CSS rem 現在我們知道 em 是什麼,讓我們看看 rem。 rem 是 CSS 中另一個測量長度的單位,代表“root em”。由於我們知道一個 em 等於當前字體大小的數值,因此我們可以推斷出“根 em”指的是根元素的字體大小,通常是 `<html>` 元素。 很困惑嗎?讓我們進一步拆解它。 與 em 一樣,rem 從父元素繼承其大小,但 rem 查看的父元素不是它上面的 div 或部分,而是包圍它的第一個元素,即 html 元素。讓我們用前面的程式碼做一個例子。相同的 html 程式碼,只是多了一個 div。 ``` <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="parent"> I'm parent div set to 20px <div class="child"> I'm the child div set to 2em, i.e 40px. </div> <div class="child-2"> I'm the child div set to 2em, i.e 60px. </div> </div> </body> </html> ``` 接下來,我們將以下 CSS 程式碼加入到我們的 CSS 文件中。 ``` html{ font-size: 30px; } .child-2{ font-size: 2rem; } ``` 結果會是這樣。 ![Image em](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/njnny8zjwbk3157hece0.png) 如您所見,儘管 child-2 div 在另一個 div 中,但它會一直往上找到 html 元素以繼承其字體大小。 使用“rem”單位允許以更具可擴展性和靈活性的方式來調整頁面上的元素大小,因為如果您更改根元素的字體大小,所有使用“rem”單位調整大小的元素將自動更新以保持它們的相對大小尺寸。 ## em 和 rem 單位的區別 到目前為止,您已經知道 em 和 rem 之間的區別,但為了清楚起見,我想重申一下這兩個值之間的區別。 在 CSS 中,rem 單位僅相對於文檔的根元素,而 em 單位僅相對於目標元素的直接父元素。這意味著 em 大小繼承自父元素,而 rem 大小僅繼承自根元素。 ## 何時在 CSS 中使用 em 和 rem 單位 對字體大小、邊距和填充等全局值使用 rem 單位是一個好主意,特別是如果你想為整個文檔指定一個字體大小並讓它統一縮放而不是受字體影響父元素的大小。 em 更適合特定於特定元素及其子元素的值。這使您可以建立一致且靈活的佈局,以適應不同的螢幕尺寸和字體大小。 ## 在 CSS 中使用 em 和 rem 單位的潛在問題 em 和 rem 是目前指定長度時使用的最佳單位,但就像生活中的所有事物一樣,它們並不完美。以下是您在使用 em 和 rem 時可能會遇到的幾個問題: - **複雜的計算:**使用 em 和 rem 單位會導致複雜的計算,尤其是當涉及嵌套元素時。這會使準確預測和控制頁面上元素的大小變得困難。 - **繼承問題:** 因為 em 單位是相對於其父元素的字體大小的,所以很難理解和控制如何在頁面上繼承大小。這可能會導致意外結果,需要額外除錯才能解決。 - **性能問題:**在極少數情況下,使用 em 和 rem 單位會對性能產生負面影響,尤其是在與復雜計算結合使用或在頁面上過度使用時。 總的來說,雖然 em 和 rem 單位在某些情況下會有所幫助,但重要的是要仔細考慮它們的潛在缺點以及它們是否是您專案的最佳選擇。

自學網頁の嬰兒教材:第1課 ── 安裝:網頁突然好美美

# 第1課 課程目標 學會安裝 Bootstrap。 # 第1課 課程內容 第一課只要學會如何安裝 Bootstrap 就可以了。 Bootstrap 安裝好之後,瀏覽器預設的 h1, h2, h3, p 等等基本元素的樣式就會被覆蓋。 會變成 Bootstrap 的預設樣式,會更漂亮。 在網頁中引入 Bootstrap 的 css 與 js 檔的方式有很多,其中最簡單的是直接引入 BootstrapCDN 的線上檔案,連下載檔案都不用。 請閱讀一些 Bootstrap 基本觀念: https://www.w3schools.com/bootstrap5/bootstrap_get_started.php https://www.w3schools.com/bootstrap5/bootstrap_typography.php 然後參考官網的 BootstrapCDN 段落: https://getbootstrap.com/docs/5.3/getting-started/download/ --- 對於引入外部檔案的觀念不熟悉的話,請參考這份的「External Style Sheet」段落: https://www.w3schools.com/css/css_howto.asp 以及這份的「JavaScript in External File」段落: https://www.tutorialspoint.com/javascript/javascript_placement.htm # 第1課 作業 請打開:[Yahoo奇摩新聞](https://tw.news.yahoo.com) 找一篇你喜歡的新聞,把新聞內容打出來。 接著打開 [Glitch](https://glitch.com/),用 Glitch 來寫這次的作業。 只要打出文章標題與內容就好,上方的導覽列、旁邊的新聞頭條那些區塊都不用。 做完之後,你會發現,雖然只用了 h1、p、br 等等基本元素,但是套用 Bootstrap 之後,整個畫面自動變漂亮了! 完成這些,你就完成這次的課程目標了!

給軟體工程師的各類好用工具清單

向您介紹這個開發人員工具列表。它是一個開源專案,由社群整理。 讓我們開始吧! 🚀 原文出處:https://dev.to/dostonnabotov/ultimate-tools-for-developers-2aj2 --- ## 程式碼編輯器和 IDE 💻 - [Visual Studio Code](https://code.visualstudio.com/) 作為免費的開源程式碼編輯器,Visual Studio Code 是開發人員的絕佳工具。它帶有許多功能和外掛,使其成為開發人員的絕佳選擇。 - [CodeSandbox](https://codesandbox.io/) 簡單來說,CodeSandbox 就是 Visual Studio Code 的在線版本。 - [Dev - Visual Studio Code](https://github.dev/) github.dev 基於網絡的編輯器是一種輕量級的編輯體驗,完全在您的瀏覽器中執行。 有兩種方法可以打開基於 Web 的編輯器 1. 在任何存儲庫或拉取請求上按 `.` 鍵 2. 將 URL 中的 .com 替換為 .dev。例如。 `https://github.dev/username/repo` - [CodePen](http://codepen.io/) CodePen 是網絡前端的遊樂場。這是一個試驗、測試和展示您的前端工作的地方。此外,您還可以從其他開發人員那裡找到許多靈感。 - [Replit](https://repl.it/) Replit 是一個簡單、強大且協作的在線 IDE。這是編碼、協作和託管專案的好地方。 - [StackBlitz](https://stackblitz.com/) 面向前端和全棧開發人員的 Web IDE。 - [TypeScript Playground](https://www.typescriptlang.org/play/) 想玩玩看 TypeScript 嗎? TypeScript Playground 是一個適合你的地方。 ## 圖片 🖼 - [Unsplash](https://unsplash.com/) 為您的下一個專案輕鬆找到精美、高質量的照片。所有照片均可免費用於商業和個人用途。 - [Pexels](https://www.pexels.com/) Pexels 是免費庫存照片的重要來源。所有照片均可免費用於商業和個人用途。 - [Carbon](https://carbon.now.sh/) Carbon 是一個很棒的平台,可以建立和共享程式碼的精美圖像,允許您使用語法突出顯示、主題、字體等自定義圖像。 ## 顏色 🎨 - [Color Space](https://mycolor.space/) 再也不會浪費時間尋找完美的調色板!只需輸入顏色!並生成漂亮的調色板 - [Coolors](https://coolors.co/) 建立完美的調色板或從數千種美麗的配色方案中汲取靈感。 - [Color Wheel](https://www.canva.com/colors/color-wheel/) 想知道什麼顏色搭配起來好看嗎? Canva 的色輪讓色彩組合變得簡單。 ## 排版 📝 - [Google Fonts](https://fonts.google.com/) Google Fonts 是一個包含免費授權字體系列的庫。只需選擇您想要的字體,將它們下載到您的計算機或使用提供的 CSS 或 HTML 鏈接將它們嵌入您的網頁。 - [Fontsource](https://fontsource.org/) 如果您不想從 CDN 獲取字體,則可以使用整齊打包的 NPM 包中的自託管開源字體。 - [Nerd Fonts](https://www.nerdfonts.com/) Nerd Fonts 使用大量字形(圖標)修補針對開發人員的字體。 ## 設計 🎨 - [Figma](https://www.figma.com/) 一個免費的線上協作界面設計工具和原型製作工具。 - [Pinterest](https://www.pinterest.com/) Pinterest 是一種視覺發現工具,可用於為您的所有專案和興趣尋找創意。 ## 文檔 📚 - [MDN 網絡文檔](https://developer.mozilla.org/en-US/) 學習Web開發的最佳平台。每當您對 HTML、CSS、JavaScript 或任何其他網絡技術有疑問時,請務必先查看 MDN。 - [W3Schools](https://www.w3schools.com/) 幾乎所有您能想到的程式語言的參考。 - [CSS 技巧](https://css-tricks.com/) 提供使用 CSS(層疊樣式表)的提示、技巧和技術的最佳平台之一。 ## 工具 🛠 等一會兒!工具中的工具?是的,你沒有聽錯。這裡有一些工具可以幫助您找到更多工具。 😃 - [Stack Overflow](https://stackoverflow.com/) Stack Overflow 是一個面向專業和狂熱工程師的問答網站。這是提出問題和獲得答案的好地方。 - [Micro Digital Tools](https://mdigi.tools/) 一組對開發人員有用的工具。 - [Small Dev Tools](https://smalldev.tools/) 一組對開發人員有用的工具。 - [Can I Use](https://caniuse.com/) Can I Use 提供了最新的瀏覽器支持表,以支持桌面和移動 Web 瀏覽器上的前端 Web 技術。 - [網站圖標生成器](https://favicon.io/) 您是否曾經為了替自己的網站建立網站圖標而苦惱?不同的尺寸,不同的格式,不同的平台。 從文本、圖像或從數百個表情符號中選擇快速生成您的網站圖標。 - [Font Awesome](https://fontawesome.com/) 免費和高級圖標庫。 - [OverAPI.com](https://overapi.com/) 以有組織的格式查找大量不同技術的備忘單。 - [Transform](https://transform.tools/) 多語言網絡轉換器。輕鬆將 HTML 轉換為 Pug、將 TypeScript 轉換為 JavaScript、將 Markdown 轉換為 HTML 等等... - [Frontend Tools](https://murtazajoo.github.io/tools/) 一個網站,您可以在其中找到具有更好用戶體驗的所有工具。 - [GitProtect](https://gitprotect.io/) 適用於所有 GitHub、GitLab、Bitbucket 和 Jira 資料的 DevOps 備份和災難恢復軟體。 - [Linear](https://linear.app/) 在團隊中組織問題和拉取請求的好工具。 ## 結論 🎉 希望您覺得這個列表有用。

36 個免費、漂亮的 React UI 模板與主題套件

網路上免費的 React 版型資源不太好找,最好有一份懶人包。 這份列表整理了各式各樣的模板與主題套件,希望對您有幫助。 - 原文出處:https://dev.to/davidepacilio/35-free-react-templates-and-themes-32ci --- ##1. Open ![](https://dev-to-uploads.s3.amazonaws.com/i/gy9nddokri1vobwrtbna.jpg) [**Live demo**](https://open.cruip.com/) / [**Download**](https://github.com/cruip/open-react-template) Open 是一個免費的 React 模板,專為開源專案、線上服務、數位產品,創建快速、專業的登陸頁面而生。為了吸引潛在客戶和電子郵件訂閱者,Open 提供了一個多功能的資源庫,其中包含時尚、簡約和可重複使用的元件和元素。 --- ##2. Atomize ![](https://dev-to-uploads.s3.amazonaws.com/i/ks2st96gb0tbu1ybuy6k.jpg) [**Live demo**](https://atomizecode.com/) / [**Download**](https://github.com/proksh/atomize) Atomize 是一個 React UI 框架,旨在幫助開發人員與設計師合作,輕鬆構建一致和諧的用戶界面。由於樣式指南和靈活網格等資源的完美結合,Atomize 適合建立任何類型的響應式網站。 --- ##3. Treact ![](https://dev-to-uploads.s3.amazonaws.com/i/3aw9a273jibs97o2l09m.jpg) [**Live demo**](https://treact.owaiskhan.me/) / [**Download**](https://gumroad.com/l/QaruQ) Treact 是使用 TailwindCSS 作為前端框架開發的現代 React 模板和 UI 組件展示庫。這個精美的檔案庫提供了 7 個內建的主頁、8 個輔助頁面以及 52 個預先設計的元素和段落。每個內容都可以針對家用電腦、平板電腦和移動設備進行擴充。 --- ##4. MatX ![](https://dev-to-uploads.s3.amazonaws.com/i/q99tvy2uvyvol2xet2et.jpg) [**Live demo**](http://matx-react.ui-lib.com/dashboard/analytics) / [**Download**](https://ui-lib.com/downloads/matx-react-dashboard/) MatX 是一個建立在 Material Design 之上的精美 React Native 模板。此模板使用 React、Redux 和 Material UI,它包含為 Web 應用程式提供新造型可能需要的所有基本功能。 MatX 的免費版本可用於輕鬆設置管理面板、用戶管理系統和專案管理系統。 --- ##5. Holly ![](https://dev-to-uploads.s3.amazonaws.com/i/dcrv1qxgo3rgq9a3j3at.jpg) [**Live demo**](https://lukemcdonald.github.io/holly-react/) / [**Download**](https://github.com/lukemcdonald/holly-react) Holly 是一個響應式 React JS 模板,適用於線上服務和數位產品的生產者,能在主要產品仍在開發中時,就開始搜集電子郵件地址。這個模板最初是由 [Cruip](https://cruip.com/) 用 HTML 設計的,然後在這個版本中用 React 撰寫。 --- ##6. OAH-Admin ![](https://dev-to-uploads.s3.amazonaws.com/i/rteeixluj4n09a3s69ma.jpg) [**Live demo**](https://oah-admin.ahmedelywa.com/extra-components/progress/) / [**Download**](https://github.com/AhmedElywa/oah-admin) OAH-Admin 是一個基於 Gatsby 的免費 React 管理儀表板模板,帶有 oah-ui 元件和元素包。這個 React 模板有良好的 UI 元件色調,超級整潔和靈活的格式使任何人都可以輕鬆建立 SaaS 應用程式、管理面板、儀表板。 --- ##7. Gatsby Starter Ghost ![](https://dev-to-uploads.s3.amazonaws.com/i/ocey043yzsdt31f7yi9s.jpg) [**Live demo**](https://gatsby.ghost.org/) / [**Download**](https://github.com/TryGhost/gatsby-starter-ghost) 使用 Ghost 這個基於 Gatsby 的入門模板,輕鬆建立高效能網站。Gatsby Starter Ghost 是一個乾淨而現代的模板,適用於部落格、雜誌或任何新聞網站。該產品專門設計來幫助任何人在網路上建立個人空間並分享想法、創意和更新。 --- ##8. Star Admin ![](https://dev-to-uploads.s3.amazonaws.com/i/hlbf4y4pl4a5od2c8chb.jpg) [**Live demo**](https://www.bootstrapdash.com/demo/star-admin-free/react/template/demo_1/preview/dashboard) / [**Download**](https://github.com/BootstrapDash/StarAdmin-Free-React-Admin-Template) 一個免費的 React Native 模板,提供了無窮無盡的各種基本元素,可以將任何想法變為現實。該模板具有精心製作的儀表板,包含大量整齊排列和組織的元件,它可以完美地與所有最新和現代的瀏覽器配合使用,並且能夠使資料可視化過程更易於管理。 --- ##9. Carolina Admin Dashboard ![](https://dev-to-uploads.s3.amazonaws.com/i/05r7fsc1jzylez5diu6f.jpg) [**Live demo**](https://demo.uifort.com/carolina-react-admin-dashboard-material-ui-free-demo/LandingPage) / [**Download**](https://uifort.com/template/carolina-react-admin-dashboard-material-ui-free/) 如果您正在尋找一個令人驚嘆且實用的 React 儀表板模板,Carolina Admin Dashboard 擁有啟動和運行您 Web 專案所需的一切。這個漂亮的模板建立在 Material-UI 框架之上,採用乾淨清新的設計,遵循所有 Google 的 Material Design 指南。此外,核心結構是完全響應式和開源的。 --- ##10. Tabler ![](https://dev-to-uploads.s3.amazonaws.com/i/nu5vq6j5buk36iz8prsn.jpg) [**Live demo**](http://tabler-react.com/) / [**Download**](https://github.com/tabler/tabler-react) Tabler 是一個免費的 React 管理儀表板模板,非常適合任何類型的後端 Web 應用。此管理模板包含大量精心設計的範例,無需從頭開始,可為您節省大量時間,它還附帶可重複使用的元件,例如按鈕、地圖、圖表、表單等。 --- ##11. React Nice Resume ![](https://dev-to-uploads.s3.amazonaws.com/i/ci5hhvp6ki5o3mpk8zbz.jpg) [**Live demo**](https://nordicgiant2.github.io/react-nice-resume-page/#home) / [**Download**](https://github.com/nordicgiant2/react-nice-resume) React Nice Resume 是一個漂亮的主題,如果您是開發人員、設計師或一般的數位創作者,可以用來宣傳您自己和您的作品。該資源展示了一個獨特的主頁,帶有粒子背景、工作經驗時間線、技能圖表、顯示最新專案的縮略圖、一個帶有功能輸入表單的段落。 --- ##12. Boss Lite ![](https://dev-to-uploads.s3.amazonaws.com/i/zq92otm0bc9t3mwinkxb.jpg) [**Live demo**](http://boss.ux-maestro.com/app/tables/data-table) / [**Download**](https://github.com/ilhammeidi/boss-lite) Boss Lite 是一個基於 React 和 Redux 的管理儀表板模板。此模板為您帶來清新現代的設計和多種配色方案。它支援大多類型的 Web 專案,並且 Flexbox 佈局而變得很流暢。 --- ##13. Chakra UI ![](https://dev-to-uploads.s3.amazonaws.com/i/poootemj2t5caoi4lryt.jpg) [**Live demo**](https://chakra-ui.com/) / [**Download**](https://github.com/chakra-ui/chakra-ui/) Chakra UI 提供了一組好用、可重用的 React 功能元件,使建立好用網站和用戶界面變得非常簡單。 Chakra UI 中的幾乎所有元素都兼容深色模式,它們遵循 WAI-ARIA 指南規範,並構建在 React UI Primitive 之上以實現無限的可組合性。 --- ##14. Black Dashboard React ![](https://dev-to-uploads.s3.amazonaws.com/i/2r1tx4uxug6k1xlnr3pr.jpg) [**Live demo**](https://demos.creative-tim.com/black-dashboard-react/#/admin/dashboard) / [**Download**](https://www.creative-tim.com/product/black-dashboard-react) Black Dashboard React 是用於管理界面的 React 模板。該模板基於 Bootstrap 建立的設計指南,是基於企業的應用程式,是強大後端軟體可用的優秀前端選項。它具有更高等級的切分、設計套件、可重複使用的圖表,能夠不斷改善用戶和開發體驗。 --- ##15. Argon Design System ![](https://dev-to-uploads.s3.amazonaws.com/i/tvrfqzddf6kwmhiwje6x.jpg) [**Live demo**](https://demos.creative-tim.com/argon-design-system-react/) / [**Download**](https://github.com/creativetimofficial/argon-design-system-react) 使用 Bootstrap 4 和 Reactstrap 的 React 設計系統。Argon Design System 帶有 100 多個單獨的元件、內建的範例,並且每個元素都有多種樣式、懸停、焦點狀態,任何人都可以輕鬆使用。該產品是從原型設計到正式上線的完美解決方案。 --- ##16. Devias Kit - Admin Dashboard ![](https://dev-to-uploads.s3.amazonaws.com/i/j7lqqfvgmujtgg1m80oi.jpg) [**Live demo**](https://react-material-dashboard.devias.io/dashboard) / [**Download**](https://github.com/devias-io/react-material-dashboard) Devias Kit 是一個響應式 Material Design 管理儀表板,專為 React 使用 Google 自己的 Material Design 框架建立。可以自定義設置、指令、圖標和樣式。該模板包含清晰直觀的目錄和文件、快速入門文件,如果您想對設計進行任何更改,甚至還有 Sketch 文件。 --- ##17. Dev Blog ![](https://dev-to-uploads.s3.amazonaws.com/i/1tym4ekzrftd6ldcflid.jpg) [**Live demo**](https://ryanfitzgerald.github.io/devblog/) / [**Download**](https://github.com/RyanFitzgerald/devblog) Dev Blog 是一個 React 網站模板,專為快速建立副專案和產品而生。該網站模板帶有一個首頁,其中顯示了部落格名稱、社交媒體圖示以及帶有文字和圖像的文章縮圖。該模板還包括單個文章頁面,有漂亮且精心策劃的排版。 --- ##18. Material PRO ![](https://dev-to-uploads.s3.amazonaws.com/i/scakf4swq5j99hln1xqx.jpg) [**Live demo**](https://wrappixel.com/demos/free-admin-templates/materialpro-reactadmin-lite/main/#/starter/starter) / [**Download**](https://www.wrappixel.com/templates/materialpro-react-admin-lite/) Material Pro 是一個免費的 React Native 模板,為任何需要管理儀表板的人精心製作。這個漂亮而清爽的產品採用模組化和現代設計理念開發,100% 免費使用和下載,並包含許多頁面,可幫助您更快、更輕鬆地建立專案。 --- ##19. Ant Design Landing ![](https://dev-to-uploads.s3.amazonaws.com/i/wnld469wyg4u9pfk31i1.jpg) [**Live demo**](https://landing.ant.design/) / [**Download**](https://github.com/ant-design/ant-design-landing) Landing 是 Ant Design System 建立的模板。內涵不同樣式的首頁和內頁模組。 --- ##20. Isomorphic ![](https://dev-to-uploads.s3.amazonaws.com/i/zy0at5stk267a06n5f95.jpg) [**Live demo**](https://isomorphic.redq.io/dashboard) / [**Download**](https://github.com/pujoey/ismorphic) Isomorphic 是一個易於管理且有吸引力的管理模板,具有大量靈活的元件。 --- ##21. Shards Dashboard Lite ![](https://dev-to-uploads.s3.amazonaws.com/i/71cn55agi3k9er11xk4o.jpg) [**Live demo**](https://designrevision.com/demo/shards-dashboard-lite-react/blog-overview) / [**Download**](https://designrevision.com/downloads/shards-dashboard-lite-react/) Shards 是一個免費的 React 儀表板模板,具有現代設計系統和許多自定義頁面和部分。 --- ##22. uiw ![](https://dev-to-uploads.s3.amazonaws.com/i/e6aakqf9m9g67mstwvi9.jpg) [**Live demo**](https://uiwjs.github.io/) / [**Download**](https://github.com/uiwjs/uiw) uiw 是用於 React 16+ 的高質量 React 元件庫和 UI 工具包。 --- ##23. React Material Admin ![](https://dev-to-uploads.s3.amazonaws.com/i/te6tezfjcp008lb4q7du.jpg) [**Live demo**](https://flatlogic.github.io/react-material-admin/#/login) / [**Download**](https://flatlogic.com/templates/react-material-admin) React Material Admin 是一個建立在 Material-UI 框架之上的 React 儀表板。 --- ##24. Material KIT React ![](https://dev-to-uploads.s3.amazonaws.com/i/cq2xlu4tci8km6p2tia7.jpg) [**Live demo**](https://demos.creative-tim.com/material-kit-react/) / [**Download**](https://www.creative-tim.com/product/material-kit-react) Material UI KIT 是一款免費的 React UI 主題,其設計靈感來自 Google 的 Material Design,設計清新整潔。 --- ##25. Airframe ![](https://dev-to-uploads.s3.amazonaws.com/i/qwt4nv73xjn14a9g09yl.jpg) [**Live demo**](http://dashboards.webkom.co/react/airframe/dashboards/projects/) / [**Download**](https://github.com/0wczar/airframe-react) Airframe 是一個基於 Bootstrap 4 和 React 16 的免費開源 React 應用程式模板。 --- ##26. Gatsby Simplefolio ![](https://dev-to-uploads.s3.amazonaws.com/i/pe3clc53zqsntgh3vw3n.jpg) [**Live demo**](https://gatsby-simplefolio.netlify.app/) / [**Download**](https://github.com/cobidev/gatsby-simplefolio) Gatsby Simplefolio 是一個乾淨、美觀且響應迅速的 React 組合模板。 --- ##27. Ant Design Pro ![](https://dev-to-uploads.s3.amazonaws.com/i/diktnddjjf630tdyyqa8.jpg) [**Live demo**](https://pro.ant.design/) / [**Download**](https://github.com/ant-design/ant-design-pro/) React --- ##28. React SaaS Template ![](https://dev-to-uploads.s3.amazonaws.com/i/yiq5ast9jw3knt8l92l0.jpg) [**Live demo**](https://reactsaastemplate.com/) / [**Download**](https://github.com/dunky11/react-saas-template) --- ##29. Shards React ![](https://dev-to-uploads.s3.amazonaws.com/i/34zfg3e4qbbzklmgr4uh.jpg) [**Live demo**](https://designrevision.com/downloads/shards-react/) / [**Download**](https://github.com/designrevision/shards-react) --- ##30. Base Web ![](https://dev-to-uploads.s3.amazonaws.com/i/8q3bxpsll7k0qrhzdlmj.jpg) [**Live demo**](https://baseweb.design/) / [**Download**](https://github.com/uber/baseweb) --- ##31. Light Blue React Dashboard ![](https://dev-to-uploads.s3.amazonaws.com/i/tfwzjgvh2sa8e5v9a0oa.jpg) [**Live demo**](https://demo.flatlogic.com/light-blue-react/#/app/main/dashboard) / [**Download**](https://github.com/flatlogic/light-blue-react-template) --- ##32. React JS Landing ![](https://dev-to-uploads.s3.amazonaws.com/i/ibuom994cxj3pzb2yzoz.jpg) [**Live demo**](https://react-landing-page-template.herokuapp.com/#page-top) / [**Download**](https://github.com/IssaafKattan/React-Landing-Page-Template) --- ##33. Admin Pro ![](https://dev-to-uploads.s3.amazonaws.com/i/0f1pjehgesa25ts39wx7.jpg) [**Live demo**](https://wrappixel.com/demos/free-admin-templates/adminpro-react-lite/main/#/dashboard) / [**Download**](https://www.wrappixel.com/templates/adminpro-react-admin-lite/#comparison) --- ##34. Blueprint ![](https://dev-to-uploads.s3.amazonaws.com/i/d1owpo8lfg3zfq1p2vpx.jpg) [**Live demo**](https://blueprintjs.com/) / [**Download**](https://github.com/palantir/blueprint) --- ##35. Datta ![](https://dev-to-uploads.s3.amazonaws.com/i/3con3tndvc7au5zg1jb0.jpg) [**Live demo**](http://lite.codedthemes.com/datta-able/react/default/dashboard/default) / [**Download**](https://codedthemes.com/item/datta-able-react-free-admin-template/) --- ##36. Flatlogic One ![](https://dev-to-uploads.s3.amazonaws.com/i/63flhvqcbh7jtfvih9do.jpg) [**Live demo**](https://flatlogic.github.io/one-react-template/#/login) / [**Download**](https://flatlogic.com/templates/one-free-react-template) --- ##結論 我希望這組免費的 React 模板和主題能夠幫助您!

7 個可以刺激網頁設計靈感的好地方:設計師、開發者推薦

身為開發者或設計師,要常常了解最新的設計趨勢,才能保持競爭力。 這邊有七個可以看到很多設計、刺激設計靈感的好地方,與您分享。 原文出處:https://dev.to/mohsenkamrani/7-websites-to-get-inspiration-for-next-level-web-design-1leg --- ## 1. https://dribbble.com 設計師社群分享網站。可以提供各種登陸頁面的設計靈感。 優點: 一個龐大而活躍的社群,大量設計可參考。 缺點:某些設計可能過於複雜或難以複製。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546361467/au1-ZogHe.png) ## 2. https://www.awwwards.com/ 展示來自世界各地的最佳設計,包括許多創意和有效的登錄頁面設計。 優點:高品質的設計,注重用戶體驗。 缺點:可能不像其他靈感來源那樣多樣化。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546444885/yExBAkGov.png) ## 3. https://www.behance.net/ 具有一系列設計組合,包括許多高品質登陸頁面的設計範例。 優點:含有大量設計稿,方便瀏覽和搜尋。 缺點:可能不像其他靈感來源那樣專注於登陸頁面。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546543511/RnNYQQKjG.png) ## 4. https://onepagelove.com/ 一個專門的網站,有很多啟發性的單頁設計,包括許多登陸頁面範例。 優點:專注於單頁設計,易於瀏覽和搜尋。 缺點:可能沒有其他靈感來源那麼多的多樣性。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546719953/9H4TBCmh8.png) ## 5. https://www.landingfolio.com/ 集合了網路上的最佳登陸頁面設計,為設計師提供豐富的靈感。 優點:大量高品質的設計,易於瀏覽和搜尋。 缺點:可能沒有其他靈感來源那麼多的多樣性。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546787563/o3nKNVT7C.png) ## 6. https://uxplanet.org/ 一個專注於使用者體驗設計的網站,包含許多精心設計的登錄頁面範例。 優點:注重用戶體驗,設計風格廣泛。 缺點:可能沒有其他靈感來源那麼多的設計。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546884319/oxqguR2Nz.png) ## 7. https://www.siteinspire.com/ 網頁設計靈感的精選集合,許多有效登錄頁面的範例。 優點:大量高品質的設計,易於瀏覽和搜尋。 缺點:可能沒有其他靈感來源那麼多的多樣性。 ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1670546938441/lXC_X5Dym.png) --- 希望您喜歡此清單,並使用它來為您的下一個專案獲得靈感。

快速複習 React 基本觀念&實務範例:推薦新手參考

React 作為一個強大的前端工具,有很多需要熟悉的基本觀念&語法。 這篇文章做一個快速的全面整理,方便工作時,可以隨時翻閱,希望您喜歡。 - 原文出處:https://dev.to/reedbarger/the-react-cheatsheet-for-2020-real-world-examples-4hgg ## 核心概念 ### 元素和 JSX - React 元素的基本語法 ``` // In a nutshell, JSX allows us to write HTML in our JS // JSX can use any valid html tags (i.e. div/span, h1-h6, form/input, etc) <div>Hello React</div> ``` - JSX 元素就是一段表達式 ``` // as an expression, JSX can be assigned to variables... const greeting = <div>Hello React</div>; const isNewToReact = true; // ... or can be displayed conditionally function sayGreeting() { if (isNewToReact) { // ... or returned from functions, etc. return greeting; // displays: Hello React } else { return <div>Hi again, React</div>; } } ``` - JSX 允許我們嵌套表達式 ``` const year = 2020; // we can insert primitive JS values in curly braces: {} const greeting = <div>Hello React in {year}</div>; // trying to insert objects will result in an error ``` - JSX 允許我們嵌套元素 ``` // to write JSX on multiple lines, wrap in parentheses: () const greeting = ( // div is the parent element <div> {/* h1 and p are child elements */} <h1>Hello!</h1> <p>Welcome to React</p> </div> ); // 'parents' and 'children' are how we describe JSX elements in relation // to one another, like we would talk about HTML elements ``` - HTML 和 JSX 的語法略有不同 ``` // Empty div is not <div></div> (HTML), but <div/> (JSX) <div/> // A single tag element like input is not <input> (HTML), but <input/> (JSX) <input name="email" /> // Attributes are written in camelcase for JSX (like JS variables <button className="submit-button">Submit</button> // not 'class' (HTML) ``` - 最基本的 React 應用程式需要三樣東西: - 1. ReactDOM.render() 渲染我們的應用程序 - 2. 一個 JSX 元素(在此情況下,稱為根節點) - 3. 一個用於掛載應用程式的 DOM 元素(通常是 index.html 文件中 id 為 root 的 div) ``` // imports needed if using NPM package; not if from CDN links import React from "react"; import ReactDOM from "react-dom"; const greeting = <h1>Hello React</h1>; // ReactDOM.render(root node, mounting point) ReactDOM.render(greeting, document.getElementById("root")); ``` ### 元件和 Props - 基本 React 元件的語法 ``` import React from "react"; // 1st component type: function component function Header() { // function components must be capitalized unlike normal JS functions // note the capitalized name here: 'Header' return <h1>Hello React</h1>; } // function components with arrow functions are also valid const Header = () => <h1>Hello React</h1>; // 2nd component type: class component // (classes are another type of function) class Header extends React.Component { // class components have more boilerplate (with extends and render method) render() { return <h1>Hello React</h1>; } } ``` - 如何使用元件 ``` // do we call these function components like normal functions? // No, to execute them and display the JSX they return... const Header = () => <h1>Hello React</h1>; // ...we use them as 'custom' JSX elements ReactDOM.render(<Header />, document.getElementById("root")); // renders: <h1>Hello React</h1> ``` - 元件可以在我們的應用程式中重複使用 ``` // for example, this Header component can be reused in any app page // this component shown for the '/' route function IndexPage() { return ( <div> <Header /> <Hero /> <Footer /> </div> ); } // shown for the '/about' route function AboutPage() { return ( <div> <Header /> <About /> <Testimonials /> <Footer /> </div> ); } ``` - 資料可以通過 props 動態傳遞給元件 ``` // What if we want to pass data to our component from a parent? // I.e. to pass a user's name to display in our Header? const username = "John"; // we add custom 'attributes' called props ReactDOM.render( <Header username={username} />, document.getElementById("root") ); // we called this prop 'username', but can use any valid JS identifier // props is the object that every component receives as an argument function Header(props) { // the props we make on the component (i.e. username) // become properties on the props object return <h1>Hello {props.username}</h1>; } ``` - Props 不可直接改變(mutate) ``` // Components must ideally be 'pure' functions. // That is, for every input, we be able to expect the same output // we cannot do the following with props: function Header(props) { // we cannot mutate the props object, we can only read from it props.username = "Doug"; return <h1>Hello {props.username}</h1>; } // But what if we want to modify a prop value that comes in? // That's where we would use state (see the useState section) ``` - 如果我們想將元素/元件作為 props 傳遞給其它元件,可以用 children props ``` // Can we accept React elements (or components) as props? // Yes, through a special property on the props object called 'children' function Layout(props) { return <div className="container">{props.children}</div>; } // The children prop is very useful for when you want the same // component (such as a Layout component) to wrap all other components: function IndexPage() { return ( <Layout> <Header /> <Hero /> <Footer /> </Layout> ); } // different page, but uses same Layout component (thanks to children prop) function AboutPage() { return ( <Layout> <About /> <Footer /> </Layout> ); } ``` - 可以用三元運算子來條件顯示元件 ``` // if-statements are fine to conditionally show , however... // ...only ternaries (seen below) allow us to insert these conditionals // in JSX, however function Header() { const isAuthenticated = checkAuth(); return ( <nav> <Logo /> {/* if isAuth is true, show AuthLinks. If false, Login */} {isAuthenticated ? <AuthLinks /> : <Login />} {/* if isAuth is true, show Greeting. If false, nothing. */} {isAuthenticated && <Greeting />} </nav> ); } ``` - Fragments 是用來顯示多個元件的特殊元件,無需向 DOM 添加額外的元素 - Fragments 適合用在條件邏輯 ``` // we can improve the logic in the previous example // if isAuthenticated is true, how do we display both AuthLinks and Greeting? function Header() { const isAuthenticated = checkAuth(); return ( <nav> <Logo /> {/* we can render both components with a fragment */} {/* fragments are very concise: <> </> */} {isAuthenticated ? ( <> <AuthLinks /> <Greeting /> </> ) : ( <Login /> )} </nav> ); } ``` ### 列表和 keys - 使用 .map() 將資料列表(陣列)轉換為元素列表 ``` const people = ["John", "Bob", "Fred"]; const peopleList = people.map(person => <p>{person}</p>); ``` - .map() 也可用來轉換為元件列表 ``` function App() { const people = ['John', 'Bob', 'Fred']; // can interpolate returned list of elements in {} return ( <ul> {/* we're passing each array element as props */} {people.map(person => <Person name={person} />} </ul> ); } function Person({ name }) { // gets 'name' prop using object destructuring return <p>this person's name is: {name}</p>; } ``` - 迭代的每個 React 元素都需要一個特殊的 `key` prop - key 對於 React 來說是必須的,以便能夠追蹤每個正在用 map 迭代的元素 - 沒有 key,當資料改變時,React 較難弄清楚元素應該如何更新 - key 應該是唯一值,才能讓 React 知道如何分辨 ``` function App() { const people = ['John', 'Bob', 'Fred']; return ( <ul> {/* keys need to be primitive values, ideally a generated id */} {people.map(person => <Person key={person} name={person} />)} </ul> ); } // If you don't have ids with your set of data or unique primitive values, // you can use the second parameter of .map() to get each elements index function App() { const people = ['John', 'Bob', 'Fred']; return ( <ul> {/* use array element index for key */} {people.map((person, i) => <Person key={i} name={person} />)} </ul> ); } ``` ### 事件和事件處理器 - React 和 HTML 中的事件略有不同 ``` // Note: most event handler functions start with 'handle' function handleToggleTheme() { // code to toggle app theme } // in html, onclick is all lowercase <button onclick="handleToggleTheme()"> Submit </button> // in JSX, onClick is camelcase, like attributes / props // we also pass a reference to the function with curly braces <button onClick={handleToggleTheme}> Submit </button> ``` - 最該先學的 React 事件是 onClick 和 onChange - onClick 處理 JSX 元素上的點擊事件(也就是按鈕動作) - onChange 處理鍵盤事件(也就是打字動作) ``` function App() { function handleChange(event) { // when passing the function to an event handler, like onChange // we get access to data about the event (an object) const inputText = event.target.value; const inputName = event.target.name; // myInput // we get the text typed in and other data from event.target } function handleSubmit() { // on click doesn't usually need event data } return ( <div> <input type="text" name="myInput" onChange={handleChange} /> <button onClick={handleSubmit}>Submit</button> </div> ); } ``` ## React Hooks ### State and useState - useState 為我們提供 function component 中的本地狀態 ``` import React from 'react'; // create state variable // syntax: const [stateVariable] = React.useState(defaultValue); function App() { const [language] = React.useState('javascript'); // we use array destructuring to declare state variable return <div>I am learning {language}</div>; } ``` - 注意:此段文章中的任何 hook 都來自 React 套件,且可以單獨導入 ``` import React, { useState } from "react"; function App() { const [language] = useState("javascript"); return <div>I am learning {language}</div>; } ``` - useState 還為我們提供了一個 `setter` 函數來更新它的狀態 ``` function App() { // the setter function is always the second destructured value const [language, setLanguage] = React.useState("python"); // the convention for the setter name is 'setStateVariable' return ( <div> {/* why use an arrow function here instead onClick={setterFn()} ? */} <button onClick={() => setLanguage("javascript")}> Change language to JS </button> {/* if not, setLanguage would be called immediately and not on click */} <p>I am now learning {language}</p> </div> ); } // note that whenever the setter function is called, the state updates, // and the App component re-renders to display the new state ``` - useState 可以在單個元件中使用一次或多次 ``` function App() { const [language, setLanguage] = React.useState("python"); const [yearsExperience, setYearsExperience] = React.useState(0); return ( <div> <button onClick={() => setLanguage("javascript")}> Change language to JS </button> <input type="number" value={yearsExperience} onChange={event => setYearsExperience(event.target.value)} /> <p>I am now learning {language}</p> <p>I have {yearsExperience} years of experience</p> </div> ); } ``` - useState 可以接受 primitive value 或物件 ``` // we have the option to organize state using whatever is the // most appropriate data type, according to the data we're tracking function App() { const [developer, setDeveloper] = React.useState({ language: "", yearsExperience: 0 }); function handleChangeYearsExperience(event) { const years = event.target.value; // we must pass in the previous state object we had with the spread operator setDeveloper({ ...developer, yearsExperience: years }); } return ( <div> {/* no need to get prev state here; we are replacing the entire object */} <button onClick={() => setDeveloper({ language: "javascript", yearsExperience: 0 }) } > Change language to JS </button> {/* we can also pass a reference to the function */} <input type="number" value={developer.yearsExperience} onChange={handleChangeYearsExperience} /> <p>I am now learning {developer.language}</p> <p>I have {developer.yearsExperience} years of experience</p> </div> ); } ``` - 如果新狀態依賴於之前的狀態,我們可以在 setter 函數中使用一個函數來為我們提供之前狀態的值 ``` function App() { const [developer, setDeveloper] = React.useState({ language: "", yearsExperience: 0, isEmployed: false }); function handleToggleEmployment(event) { // we get the previous state variable's value in the parameters // we can name 'prevState' however we like setDeveloper(prevState => { return { ...prevState, isEmployed: !prevState.isEmployed }; // it is essential to return the new state from this function }); } return ( <button onClick={handleToggleEmployment}>Toggle Employment Status</button> ); } ``` ### side effects 和 useEffect - useEffect 讓我們在 function component 中執行副作用。什麼是副作用? - 副作用是我們需要接觸外部世界的地方。例如,從 API 獲取資料或操作 DOM。 - 副作用是可能以不可預測的方式,改變我們元件狀態的操作(導致「副作用」)。 - useEffect 接受 callback function(稱為 effect 函數),預設情況下,每次重新渲染時都會運行 - useEffect 在我們的元件載入後運行,可以準確在元件的各個生命週期觸發 ``` // what does our code do? Picks a color from the colors array // and makes it the background color function App() { const [colorIndex, setColorIndex] = React.useState(0); const colors = ["blue", "green", "red", "orange"]; // we are performing a 'side effect' since we are working with an API // we are working with the DOM, a browser API outside of React useEffect(() => { document.body.style.backgroundColor = colors[colorIndex]; }); // whenever state is updated, App re-renders and useEffect runs function handleChangeIndex() { const next = colorIndex + 1 === colors.length ? 0 : colorIndex + 1; setColorIndex(next); } return <button onClick={handleChangeIndex}>Change background color</button>; } ``` - 如果不想在每次渲染後都執行 callback function,可以在第二個參數傳一個空陣列 ``` function App() { ... // now our button doesn't work no matter how many times we click it... useEffect(() => { document.body.style.backgroundColor = colors[colorIndex]; }, []); // the background color is only set once, upon mount // how do we not have the effect function run for every state update... // but still have it work whenever the button is clicked? return ( <button onClick={handleChangeIndex}> Change background color </button> ); } ``` - useEffect 讓我們能夠在 dependencies 陣列的內容改變時,才執行 - dependencies 陣列是第二個參數,如果陣列中的任何一個值發生變化,effect function 將再次運行 ``` function App() { const [colorIndex, setColorIndex] = React.useState(0); const colors = ["blue", "green", "red", "orange"]; // we add colorIndex to our dependencies array // when colorIndex changes, useEffect will execute the effect fn again useEffect(() => { document.body.style.backgroundColor = colors[colorIndex]; // when we use useEffect, we must think about what state values // we want our side effect to sync with }, [colorIndex]); function handleChangeIndex() { const next = colorIndex + 1 === colors.length ? 0 : colorIndex + 1; setColorIndex(next); } return <button onClick={handleChangeIndex}>Change background color</button>; } ``` - 可以在 useEffect 最後回傳一個函數,來取消訂閱某些效果 ``` function MouseTracker() { const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 }); React.useEffect(() => { // .addEventListener() sets up an active listener... window.addEventListener("mousemove", handleMouseMove); // ...so when we navigate away from this page, it needs to be // removed to stop listening. Otherwise, it will try to set // state in a component that doesn't exist (causing an error) // We unsubscribe any subscriptions / listeners w/ this 'cleanup function' return () => { window.removeEventListener("mousemove", handleMouseMove); }; }, []); function handleMouseMove(event) { setMousePosition({ x: event.pageX, y: event.pageY }); } return ( <div> <h1>The current mouse position is:</h1> <p> X: {mousePosition.x}, Y: {mousePosition.y} </p> </div> ); } // Note: we could extract the reused logic in the callbacks to // their own function, but I believe this is more readable ``` - 使用 useEffect 撈取資料 - 請注意,如果要使用更簡潔的 async/awit 語法處理 promise,則需要建立一個單獨的函數(因為 effect callback function 不能是 async) ``` const endpoint = "https://api.github.com/users/codeartistryio"; // with promises: function App() { const [user, setUser] = React.useState(null); React.useEffect(() => { // promises work in callback fetch(endpoint) .then(response => response.json()) .then(data => setUser(data)); }, []); } // with async / await syntax for promise: function App() { const [user, setUser] = React.useState(null); // cannot make useEffect callback function async React.useEffect(() => { getUser(); }, []); // instead, use async / await in separate function, then call // function back in useEffect async function getUser() { const response = await fetch("https://api.github.com/codeartistryio"); const data = await response.json(); setUser(data); } } ``` ### 效能和 useCallback - useCallback 是一個用來提高元件性能的 hook - 如果你有一個經常重新渲染的元件,useCallback 可以防止元件內的 callback function 在每次元件重新渲染時都重新創建(導致元件重新運行) - useCallback 僅在其依賴項之一改變時重新運行 ``` // in Timer, we are calculating the date and putting it in state a lot // this results in a re-render for every state update // we had a function handleIncrementCount to increment the state 'count'... function Timer() { const [time, setTime] = React.useState(); const [count, setCount] = React.useState(0); // ... but unless we wrap it in useCallback, the function is // recreated for every single re-render (bad performance hit) // useCallback hook returns a callback that isn't recreated every time const inc = React.useCallback( function handleIncrementCount() { setCount(prevCount => prevCount + 1); }, // useCallback accepts a second arg of a dependencies array like useEffect // useCallback will only run if any dependency changes (here it's 'setCount') [setCount] ); React.useEffect(() => { const timeout = setTimeout(() => { const currentTime = JSON.stringify(new Date(Date.now())); setTime(currentTime); }, 300); return () => { clearTimeout(timeout); }; }, [time]); return ( <div> <p>The current time is: {time}</p> <p>Count: {count}</p> <button onClick={inc}>+</button> </div> ); } ``` ### Memoization 和 useMemo - useMemo 和 useCallback 非常相似,都是為了提高效能。但就不是為了暫存 callback function,而是為了暫存耗費效能的運算結果 - useMemo 允許我們「記憶」已經為某些輸入進行了昂貴計算的結果(之後就不用重新計算了) - useMemo 從計算中回傳一個值,而不是 callback 函數(但可以是一個函數) ``` // useMemo is useful when we need a lot of computing resources // to perform an operation, but don't want to repeat it on each re-render function App() { // state to select a word in 'words' array below const [wordIndex, setWordIndex] = useState(0); // state for counter const [count, setCount] = useState(0); // words we'll use to calculate letter count const words = ["i", "am", "learning", "react"]; const word = words[wordIndex]; function getLetterCount(word) { // we mimic expensive calculation with a very long (unnecessary) loop let i = 0; while (i < 1000000) i++; return word.length; } // Memoize expensive function to return previous value if input was the same // only perform calculation if new word without a cached value const letterCount = React.useMemo(() => getLetterCount(word), [word]); // if calculation was done without useMemo, like so: // const letterCount = getLetterCount(word); // there would be a delay in updating the counter // we would have to wait for the expensive function to finish function handleChangeIndex() { // flip from one word in the array to the next const next = wordIndex + 1 === words.length ? 0 : wordIndex + 1; setWordIndex(next); } return ( <div> <p> {word} has {letterCount} letters </p> <button onClick={handleChangeIndex}>Next word</button> <p>Counter: {count}</p> <button onClick={() => setCount(count + 1)}>+</button> </div> ); } ``` ### Refs 和 useRef - Refs 是所有 React 組件都可用的特殊屬性。允許我們在元件安裝時,創建針對特定元素/元件的引用 - useRef 允許我們輕鬆使用 React refs - 我們在元件開頭呼叫 useRef,並將回傳值附加到元素的 ref 屬性來引用它 - 一旦我們創建了一個引用,就可以用它來改變元素的屬性,或者可以呼叫該元素上的任何可用方法(比如用 .focus() 來聚焦) ``` function App() { const [query, setQuery] = React.useState("react hooks"); // we can pass useRef a default value // we don't need it here, so we pass in null to ref an empty object const searchInput = useRef(null); function handleClearSearch() { // current references the text input once App mounts searchInput.current.value = ""; // useRef can store basically any value in its .current property searchInput.current.focus(); } return ( <form> <input type="text" onChange={event => setQuery(event.target.value)} ref={searchInput} /> <button type="submit">Search</button> <button type="button" onClick={handleClearSearch}> Clear </button> </form> ); } ``` ## 進階 Hook ### Context 和 useContext - 在 React 中,盡量避免創建多個 props 來將資料從父元件向下傳遞兩個或多個層級 ``` // Context helps us avoid creating multiple duplicate props // This pattern is also called props drilling: function App() { // we want to pass user data down to Header const [user] = React.useState({ name: "Fred" }); return ( // first 'user' prop <Main user={user} /> ); } const Main = ({ user }) => ( <> {/* second 'user' prop */} <Header user={user} /> <div>Main app content...</div> </> ); const Header = ({ user }) => <header>Welcome, {user.name}!</header>; ``` - Context 有助於將 props 從父組件向下傳遞到多個層級的子元件 ``` // Here is the previous example rewritten with Context // First we create context, where we can pass in default values const UserContext = React.createContext(); // we call this 'UserContext' because that's what data we're passing down function App() { // we want to pass user data down to Header const [user] = React.useState({ name: "Fred" }); return ( {/* we wrap the parent component with the provider property */} {/* we pass data down the computer tree w/ value prop */} <UserContext.Provider value={user}> <Main /> </UserContext.Provider> ); } const Main = () => ( <> <Header /> <div>Main app content...</div> </> ); // we can remove the two 'user' props, we can just use consumer // to consume the data where we need it const Header = () => ( {/* we use this pattern called render props to get access to the data*/} <UserContext.Consumer> {user => <header>Welcome, {user.name}!</header>} </UserContext.Consumer> ); ``` - useContext hook 可以移除這種看起來很怪的 props 渲染模式,同時又能在各種 function component 中隨意使用 ``` const Header = () => { // we pass in the entire context object to consume it const user = React.useContext(UserContext); // and we can remove the Consumer tags return <header>Welcome, {user.name}!</header>; }; ``` ### Reducers 和 useReducer - Reducers 是簡單、可預測的(純)函數,它接受一個先前的狀態物件和一個動作物件,並回傳一個新的狀態物件。例如: ``` // let's say this reducer manages user state in our app: function reducer(state, action) { // reducers often use a switch statement to update state // in one way or another based on the action's type property switch (action.type) { // if action.type has the string 'LOGIN' on it case "LOGIN": // we get data from the payload object on action return { username: action.payload.username, isAuth: true }; case "SIGNOUT": return { username: "", isAuth: false }; default: // if no case matches, return previous state return state; } } ``` - Reducers 是一種強大的狀態管理模式,用於流行的 Redux 狀態管理套件(這套很常與 React 一起使用) - 與 useState(用於本地元件狀態)相比,Reducers 可以通過 useReducer hook 在 React 中使用,以便管理我們應用程序的狀態 - useReducer 可以與 useContext 配對來管理資料並輕鬆地將資料傳遞給元件 - useReducer + useContext 可以當成應用程式的整套狀態管理系統 ``` const initialState = { username: "", isAuth: false }; function reducer(state, action) { switch (action.type) { case "LOGIN": return { username: action.payload.username, isAuth: true }; case "SIGNOUT": // could also spread in initialState here return { username: "", isAuth: false }; default: return state; } } function App() { // useReducer requires a reducer function to use and an initialState const [state, dispatch] = useReducer(reducer, initialState); // we get the current result of the reducer on 'state' // we use dispatch to 'dispatch' actions, to run our reducer // with the data it needs (the action object) function handleLogin() { dispatch({ type: "LOGIN", payload: { username: "Ted" } }); } function handleSignout() { dispatch({ type: "SIGNOUT" }); } return ( <> Current user: {state.username}, isAuthenticated: {state.isAuth} <button onClick={handleLogin}>Login</button> <button onClick={handleSignout}>Signout</button> </> ); } ``` ### 編寫 custom hooks - 創建 hook 就能輕鬆在元件之間重用某些行為 - hook 是一種比以前的 class component 更容易理解的模式,例如 higher-order components 或者 render props - 根據需要,隨時可以自創一些 hook ``` // here's a custom hook that is used to fetch data from an API function useAPI(endpoint) { const [value, setValue] = React.useState([]); React.useEffect(() => { getData(); }, []); async function getData() { const response = await fetch(endpoint); const data = await response.json(); setValue(data); }; return value; }; // this is a working example! try it yourself (i.e. in codesandbox.io) function App() { const todos = useAPI("https://todos-dsequjaojf.now.sh/todos"); return ( <ul> {todos.map(todo => <li key={todo.id}>{todo.text}</li>)} </ul> ); } ``` ### Hooks 規則 - 使用 React hooks 有兩個核心規則,要遵守才能正常運作: - 1. Hooks 只能在元件開頭呼叫 - Hooks 不能放在條件、迴圈或嵌套函數中 - 2. Hooks只能在 function component 內部使用 - Hooks 不能放在普通的 JavaScript 函數或 class component 中 ``` function checkAuth() { // Rule 2 Violated! Hooks cannot be used in normal functions, only components React.useEffect(() => { getUser(); }, []); } function App() { // this is the only validly executed hook in this component const [user, setUser] = React.useState(null); // Rule 1 violated! Hooks cannot be used within conditionals (or loops) if (!user) { React.useEffect(() => { setUser({ isAuth: false }); // if you want to conditionally execute an effect, use the // dependencies array for useEffect }, []); } checkAuth(); // Rule 1 violated! Hooks cannot be used in nested functions return <div onClick={() => React.useMemo(() => doStuff(), [])}>Our app</div>; } ``` --- 以上是快速整理,希望對您有幫助!

10 個可以學習 JavaScript 的互動式網頁遊戲

利用玩遊戲來學習程式語言,不但好玩,還可以視覺化學習。 來看看這十個遊戲吧! - 原文出處:https://dev.to/dailydevtips1/10-games-to-learn-javascript-155j ## 1.CodinGame ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1669180583597/1D_NywE8W.png) CodinGame 是一個多語言平台,可以邊玩遊戲邊學多種程式語言,包括 JavaScript。 最酷的是有多人模式,可以跟朋友或同事一起玩。 https://www.codingame.com/ide/puzzle/onboarding ## 2.CodeCombat ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1669180891032/OPOCUVmSM.png) CodeCombat 是一款 RPG 遊戲,可以學習網路基礎知識、程式語言,等等電腦觀念。 基本關卡免費,付費可以解鎖更多學習關卡。 https://codecombat.com/play/level/dungeons-of-kithgard ## 3.Untrusted ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1669181105367/mEnfeBOA0.png) 這遊戲把命令列視窗變成密室逃脫。 需要輸入 JavaScript 程式碼才能通關。很容易讓手,也有很多提示。 https://alexnisnevich.github.io/untrusted/ ## 4.Codewars ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1669181416059/mshCexo8U.png) 通過填空來解決關卡。 可以跟別人討論、查看別人的解法。 很適合學習、發展新技能。 https://www.codewars.com/dashboard ## 5.JSRobot ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1669181700097/ANwMAnMU5.png) JSRobot 需要輸入 JavaScript 來控制機器人、清除關卡。 https://lab.reaal.me/jsrobot/#level=1&language=en ## 6.JSDares ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1669181942194/FgsC6Zo8M.png) JSDares 是一個開源遊戲平台,上面的關卡都是社群提供的。 都是小遊戲,可以每天早上玩一點。 很值得一試的遊戲平台! https://jsdares.com/ ## 7.Screeps ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1669182404647/2kevLRBHA.png) Screeps 是一款沙盒遊戲,寫 JavaScript 來控制一個殖民地。 可以學習 JavaScript 的各種方面。 關卡很多,內容龐大的遊戲。 https://screeps.com/a/#!/sim/tutorial/1 ## 8.Crunchzilla ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1669182635041/KvPpkah2d.png) Crunchzilla 有大量的圖形說明、多種難度關卡,可以逐步學習。 利用大量視覺說明,來解釋程式語言觀念。 https://www.crunchzilla.com/code-maven ## 9.Elevator Saga ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1669182844012/hF13igJGy.png) 這是個電梯遊戲,需要寫 JavaScript 來運送乘客。 有很多關卡跟說明文件。 可以不斷改進解法,來讓電梯更有效率 https://play.elevatorsaga.com/ ## 10.CheckIO ![](https://cdn.hashnode.com/res/hashnode/image/upload/v1669183173116/Yi7hnNf-0.png) CheckIO 會顯示各種解決方法,可以看到不止一種寫程式的方法。 有助於了解各種解法以及優化方案。 https://js.checkio.org/ --- 感謝閱讀,希望對您有幫助!