🔍 搜尋結果:user

🔍 搜尋結果:user

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

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

後端 JS 訓練二:第6課 ── 回應 http post request

## 課程目標 - 使用 node 與 express 回應 http post request ## 課程內容 前面幾課我們學習了 http get 的寫法,這次來學 http post 的寫法 在「會更新主機資料狀態」的操作時,通常都會用 http post 例如,新增資料、更新資料、刪除資料,等等常見操作! 通常主機資料狀態會放在「資料庫軟體」例如 mysql 裡面,我們簡單起見,放在一個 json 檔案就好! --- 替這課建立 lesson6 資料夾,內容跟 lesson5 一樣即可 新增一個 new.ejs 檔案,放入以下內容 ``` <h1>新同學報到!</h1> <form method="post" action="/create"> name: <input type="text" name="name"> </form> ``` 然後在 index.js 加入這段程式碼 ``` const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: true })); app.get('/new', function(req, res){ res.render('new'); }); app.post('/create', (req, res) => { const fs = require('fs'); const name = req.body.name; const data = fs.readFileSync('./lesson6/users.json'); const users = JSON.parse(data); users.push({ name: name }); fs.writeFileSync('./lesson6/users.json', JSON.stringify(users)); res.send('<h1>新增成功!</h1>'); }) ``` 然後去終端機輸入 ``` node lesson6/index.js ``` 接著打開瀏覽器,在網址輸入 ``` http://localhost:3000/new ``` 你會看到新增同學的頁面與表單! 輸入姓名之後,送出表單就可以新增同學的資料了! --- 開頭跟 bodyParser 有關的兩行,要引入並設定好,才能使用 req.body 的參數 為什麼要加這兩行?這跟 express 的 middleware 機制設計有關,這邊不深入說明 反正就是在需要使用某些功能的時候,express 不會預設通通提供給你,要請你去設定啟用之後,才會支援 --- 之前處理 http get 的 url 參數時,我們使用 req.query 來取得參數 這次處理 http post 的表單參數時,我們使用 req.body 來取得參數 express 會這樣設計,是因為在 http 協定中,這兩種參數本來就放在不同地方喔! 看不太懂沒關係,先照做就對了! --- 檔案處理、新增資料放進 json 檔案的段落,跟之前的課程一樣,忘記的話就回頭翻閱一下吧! ## 課後作業 這次要開發「新增文章」的功能 並且練習用 node 回應 http post request 請把 hw5 的內容複製到 hw6,然後增加 new.ejs 檔案 ``` /repo /hw6 /index.js /homepage.ejs /view.ejs /new.ejs /posts.json /public /style.css ``` 接著修改主程式 index.js 的內容,讓網站能夠回應 `/new` 這個網址 這網址會把 new.ejs 的內容 render 出來,內容就放一個 form 表單 表單內可輸入 `標題` 以及 `文章內容`,點擊送出按鈕會以 http post 的形式發送到 `/create` 接著修改主程式 index.js 的內容,讓網站能夠回應 `/create` 這個網址 將接收到的資料,存進 `posts.json` 裡面 完成以上任務,你就完成這次的課程目標了! --- 在上傳到 github 時,你會注意到因為 `posts.json` 有改變,所以會帶著新資料一起上傳,好像有點怪? 其實,實務上會把資料存在 mysql 這類專門資料庫軟體,不會這樣存在 json 檔案中 本課程為了簡化,所以直接存在 json 檔案,這不是實務正常做法~ 為了方便起見,每次新增文章 `posts.json` 都會改變,就都一起上傳,沒關係~

後端 JS 訓練二:第5課 ── 處理 url 參數

## 課程目標 - 使用 node 與 express 處理 url 參數 ## 課程內容 在瀏覽網站的時候,點擊不同頁面時,有時需要透過 url(網址)附帶一些參數 這課來學習如何用 node 處理 url 參數 替這課建立 lesson5 資料夾,內容跟 lesson4 一樣即可 在 index.js 加入這段程式碼 ``` app.get('/view', (req, res) => { const data = fs.readFileSync('./lesson5/users.json'); const users = JSON.parse(data); const index = req.query.index; const user = users[index]; res.send('<h1>' + user.name + '同學,你好!</h1>'); }); ``` 然後把 hello.ejs 的內容修改成 ``` <div> <% for(var i = 0; i < users.length; i++) { %> <p> <%= users[i].name %>同學,你好! <a href="/view?index=<%= i %>">單獨打招呼頁面</a> </p> <% } %> </div> ``` 然後去終端機輸入 ``` node lesson5/index.js ``` 接著打開瀏覽器,在網址輸入 ``` http://localhost:3000/ ``` 你會看到每段訊息旁邊,多了一個單獨連結,點下去,就會到單獨打招呼頁面! 操作看看吧!試試看「透過網址傳參數」的感覺! --- 在 http 協定中,網址中出現問號 `?` 代表後面的部份是參數,參數的值應該可以單獨被抓出來 前面說過 `(req, res)` ,很多人會寫 `(request, response)`,兩者意思一樣,就是在 express 中代表請求&回應的物件 這邊是我們第一次使用「請求」物件!我們在請求物件中,使用 `req.query.index` 找出名為 `index` 的參數 然後在首頁,透過迴圈,加上每個單獨頁面的連結,通通使用 `index` 作為參數傳遞 --- 實務上,開發後端應用時,只要是 http get request,有時會透過網址本身代表參數,例如 ``` /view/1 /view/2 /view/3 ``` 有時會透過 url parameter 傳遞參數,例如 ``` /view?id=1 /view?id=2 /view?id=3 ``` 這是一個主觀偏好問題,其實都可以!效果也差不多 這兩種寫法,在各種程式語言中,處理起來有點不一樣 本課就以 url parameter 作為示範,先照做即可,別擔心! ## 課後作業 這次要開發「閱讀單篇文章」的功能 並且練習 url 參數的傳遞&取得 請把 hw4 的內容複製到 hw5,然後增加 view.ejs 檔案 ``` /repo /hw5 /index.js /homepage.ejs /view.ejs /posts.json /public /style.css ``` 修改部落格首頁,替每篇文章加上 <a> 超連結,點擊之後會前往單篇文章的網址 舉例來說,第一篇文章的網址會是 ``` <a href="/view?index=0"> ``` 第二篇的網址會是 ``` <a href="/view?index=1"> ``` 第三篇的網址會是 ``` <a href="/view?index=2"> ``` 接著修改主程式 index.js 的內容,讓網站能夠回應 `/view` 這種網址 然後根據從網址取得的索引參數,找出 posts.json 中對應的文章資料 接著把資料放進 view.ejs 模板中,回應顯示為網頁 請自行設計 view.ejs 的內容,簡單顯示一篇文章內容即可 請稍微加上一點樣式,弄得漂亮一點! 完成以上任務,你就完成這次的課程目標了!

後端 JS 訓練二:第4課 ── 提供靜態檔案

## 課程目標 - 使用 node 與 express 提供靜態檔案 ## 課程內容 目前為止的網頁,都是純 html,太陽春了! 這一課來學習,如何用 node 來提供 css 或圖片之類的「靜態檔案」! 替這課建立 lesson4 資料夾,內容跟 lesson3 同樣之外,再建立一個 public 資料夾,裡面新增 style.css 檔案 ``` /repo /lesson4 /index.js /hello.ejs /users.json /public /style.css ``` 在 index.js 裡面多加一行程式碼 ``` app.use(express.static('./lesson4/public')); ``` 在 style.css 裡面加入一些樣式 ``` p { color: green; } ``` 接著在 hello.ejs 加入樣式連結 ``` <link rel="stylesheet" href="/style.css"> ``` 然後去終端機輸入 ``` node lesson4/index.js ``` 接著打開瀏覽器,在網址輸入 ``` http://localhost:3000/ ``` 你會看到原本的打招呼訊息,文字變成了綠色! --- 後端程式設計,不論何種程式語言,在提供圖片、css 這種靜態檔案的時候,通常會開一個獨立的 public 資料夾來放檔案 所以本課使用的 `app.use(express.static('./lesson4/public'));` 程式碼 就只是設定一下,請 express 從某個資料夾提供靜態檔案,就這樣而已! ## 課後作業 這次要練習用 node 回應靜態檔案 請把 hw3 的內容複製到 hw4,然後增加 public 資料夾與 style.css 檔案 ``` /repo /hw4 /index.js /homepage.ejs /posts.json /public /style.css ``` 請在 style.css 中,稍微替你的日記首頁加一些樣式,弄得漂亮一點! 完成以上任務,你就完成這次的課程目標了!

後端 JS 訓練二:第3課 ── 使用 ejs 模板並讀取變數

## 課程目標 - 使用 ejs 模板並讀取變數 ## 課程內容 這一課來學習如何讀取變數之後,放進 ejs 模板呈現! 先來安裝之前用過的 readline-sync 套件 ``` npm install readline-sync ``` 替這課建立一個資料夾,然後建立 `index.js` `hello.ejs` `users.json` 這幾個檔案 此時資料夾會長類似這樣 ``` repo ├── package.json ├── package-lock.json ├── node_modules ├── lesson1 │   └── index.js ├── lesson2 │ ├── hello.ejs │   └── index.js └── lesson3 ├── users.json ├── hello.ejs    └── index.js ``` 在 users.json 放入以下內容 ``` [ { "name": "小明", }, { "name": "小華", }, { "name": "小王", } ] ``` 在 hello.ejs 放入以下內容 ``` <div> <% for(var i = 0; i < users.length; i++) { %> <p> <%= users[i].name %>同學,你好! </p> <% } %> </div> ``` 在 index.js 放入以下內容 ``` const express = require('express'); const app = express(); const engine = require('ejs-locals'); const fs = require('fs'); app.engine('ejs', engine); app.set('views', './lesson3'); app.set('view engine', 'ejs'); app.get('/', function(req, res){ const data = fs.readFileSync('./lesson3/users.json'); const users = JSON.parse(data); res.render('hello', { users: users }); }); app.listen(3000); ``` 然後去終端機輸入 ``` node lesson3/index.js ``` 接著打開瀏覽器,在網址輸入 ``` http://localhost:3000/ ``` 你會看到很多則訊息,分別跟多位同學打招呼! --- 這段程式不用我多加說明了吧!檔案讀取也是之前教過的內容! 這邊唯一多學的東西,就是 ejs 關於 for 迴圈的語法,反正就是 `<%` 跟 `%>` 之類的東西包起來而已 ejs 還有支援很多豐富的語法&功能,有興趣的話,自行研究一下吧! ## 課後作業 這次要練習匯入資料到 ejs 模板 請新建立 hw3 資料夾,採用以下結構 ``` /repo /hw3 /index.js /homepage.ejs /posts.json ``` 請修改 homepage.ejs 內容,將文章內容移出來,放在 posts.json 裡面 ``` [ { "title": "第一篇日記", "content": "今天天氣很好,夏天太陽很大,讓我心情很好" }, { "title": "第二篇日記", "content": "早起出門運動,回家沖個澡,整天心情很好" }, { "title": "第三篇日記", "content": "下大雨一整天,整天在家追劇,滿舒服的" } ] ``` 這樣 homepage.ejs 內就不會只是 html 了,你會練習到 ejs 獨有的模板語法! 完成以上任務,你就完成這次的課程目標了! --- 請更新你的 github 專案內容,此時應該變成這樣 ``` /repo /hw1 /index.js /hw2 /index.js /homepage.ejs /hw3 /index.js /homepage.ejs /posts.json ``` 依此類推,之後就這樣交作業!

改善重用性:Vue Composables 的推薦技巧&Design Patterns

本文將分為三個部分: 1. 通用設計模式 2. 我的建議 3. 進一步閱讀 享受並且讓我知道您在專案中使用的模式和實踐🚀 原文出處:https://dev.to/jacobandrewsky/good-practices-and-design-patterns-for-vue-composables-24lk ## 通用設計模式 我認為了解建置可組合項模式的最佳來源實際上是 Vue.js 文件,您可以在[此處](https://vuejs.org/guide/reusability/composables.html)查看 ### 基本可組合項 Vue 文件顯示了以下 useMouse 可組合項的示例: ``` // mouse.js import { ref, onMounted, onUnmounted } from 'vue' // by convention, composable function names start with "use" export function useMouse() { // state encapsulated and managed by the composable const x = ref(0) const y = ref(0) // a composable can update its managed state over time. function update(event) { x.value = event.pageX y.value = event.pageY } // a composable can also hook into its owner component's // lifecycle to setup and teardown side effects. onMounted(() => window.addEventListener('mousemove', update)) onUnmounted(() => window.removeEventListener('mousemove', update)) // expose managed state as return value return { x, y } } ``` 稍後可以在元件中使用它,如下所示: ``` <script setup> import { useMouse } from './mouse.js' const { x, y } = useMouse() </script> <template>Mouse position is at: {{ x }}, {{ y }}</template> ``` ### 異步可組合項 為了獲取資料,Vue 建議使用以下可組合結構: ``` import { ref, watchEffect, toValue } from 'vue' export function useFetch(url) { const data = ref(null) const error = ref(null) watchEffect(() => { // reset state before fetching.. data.value = null error.value = null // toValue() unwraps potential refs or getters fetch(toValue(url)) .then((res) => res.json()) .then((json) => (data.value = json)) .catch((err) => (error.value = err)) }) return { data, error } } ``` 然後可以在元件中使用它,如下所示: ``` <script setup> import { useFetch } from './fetch.js' const { data, error } = useFetch('...') </script> ``` ### 可組合合約 根據上面的示例,以下是所有可組合項都應遵循的約定: 1. 可組合文件名應以 use 開頭,例如 `useSomeAmazingFeature.ts` 2. 它可以接受輸入參數,這些參數可以是字串等基本類型,也可以接受 refs 和 getter,但需要使用 toValue 幫助器 3. Composable 應該返回一個 ref 值,該值可以在解構可組合項後存取,例如 `const { x, y } = useMouse()` 4. 可組合項可以保存可以在整個應用程式中存取和修改的全局狀態。 5. 可組合性可能會產生副作用,例如加入窗口事件偵聽器,但在卸載元件時應清除它們。 6. 可組合項只能在 `<script setup>` 或 `setup()` 掛鉤中呼叫。它們也應該在這些上下文中同步呼叫。在某些情況下,您還可以在生命週期掛鉤中呼叫它們,例如“onMounted()”。 7. 可組合項可以呼叫內部的其他可組合項。 8. 可組合項應在內部包裝某些邏輯,當過於復雜時,應將它們提取到單獨的可組合項中以便於測試。 ## 我的建議 我已經為我的工作專案和開源專案建置了多個可組合項 - NuxtAlgolia、NuxtCloudinary、NuxtMedusa,因此基於這些,我想根據我的經驗在上面的合同中加入一些要點。 ### 有狀態或/和純函數可組合項 在程式碼標準化的某個時刻,您可能會得出這樣的結論:您希望對可組合項中的狀態保留做出決定。 最容易測試的函數是那些不存儲任何狀態的函數(即它們是簡單的輸入/輸出函數),例如負責將字節轉換為人類可讀值的可組合函數。它接受一個值並返回一個不同的值 - 它不存儲任何狀態。 不要誤會我的意思,你不必做出“或”的決定。您可以完全保留有狀態和無狀態可組合項。但這應該是一個書面決定,以便以後更容易與他們合作 🙂 ### 可組合項的單元測試 我們希望使用 Vitest 為我們的前端應用程式實施單元測試。在後端工作時,進行單元測試程式碼覆蓋率非常有用,因為您主要關注邏輯。然而,在前端,您通常使用視覺效果。 因此,我們認為對整個元件進行單元測試可能不是最好的主意,因為我們基本上將對框架本身進行單元測試(如果按下按鈕,檢查狀態是否更改或模式是否打開)。 由於我們已將所有業務邏輯移至可組合項(基本上是 TypeScript 函數)內,因此它們很容易使用 Vitest 進行測試,並且允許我們擁有更穩定的系統。 ### 可組合項的範圍 不久前,在 VueStorefront 中,我們開發了自己的可組合方法(早在它們實際上像這樣被呼叫之前)。在我們的方法中,我們使用可組合項來映射電子商務的業務領域,如下所示: ``` const { cart, load, addItem, removeItem, remove, ... } = useCart() ``` 這種方法絕對有用,因為它允許將域包裝在一個函數中。在“useProduct”或“useCategory”等更簡單的示例中,實現和維護相對簡單。然而,正如您在此處的“useCart”示例中看到的那樣,當包裝一個包含更多邏輯而不僅僅是資料獲取的域時,這個可組合項正在發展成為一種非常難以開發和維護的形狀。 此時,我開始為 Nuxt 生態系統做出貢獻,其中引入了不同的方法。在這種新方法中,每個可組合項僅負責一件事。因此,我們的想法不是建置一個巨大的“useCart”可組合項,而是為每個功能建置可組合項,即“useAddToCart”、“useFetchCart”、“useRemovefromCart”等。 因此,維護和測試這些可組合項應該更容易 🙂 ## 進一步閱讀 這將是我的研究的全部內容。如果您想了解有關此主題的更多訊息,請務必查看以下文章: * https://vuejs.org/guide/reusability/composables.html * https://www.youtube.com/watch?v=bcZM3EogPJE * https://vueschool.io/articles/vuejs-tutorials/what-is-a-vue-js-composable/ * https://blog.logrocket.com/getting-started-vue-composables/ * https://macopedia.com/blog/news/how-can-vue-3-composables-make-your-life-easier

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

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

7 個進階、好用的 TypeScript 技巧用法分享

**TypeScript** 是一種出色的工具,可以讓我們的生活更輕鬆並避免 **bug**,但有時使用起來感覺不知所措。 本文概述了專業人士使用的 7 個 **TypeScript** 技巧,它們將使您的生活更輕鬆。 原文出處:https://dev.to/ruppysuppy/7-secret-typescript-tricks-pros-use-3ckg ## 1. 型別推理 **Typescript** 足夠聰明,可以在您幫助縮小資料類型時**推斷資料類型**。 ``` enum CounterActionType { Increment = "INCREMENT", IncrementBy = "INCREMENT_BY", } interface IncrementAction { type: CounterActionType.Increment; } interface IncrementByAction { type: CounterActionType.IncrementBy; payload: number; } type CounterAction = | IncrementAction | IncrementByAction; function reducer(state: number, action: CounterAction) { switch (action.type) { case CounterActionType.Increment: // TS infers that the action is IncrementAction // & has no payload return state + 1; case CounterActionType.IncrementBy: // TS infers that the action is IncrementByAction // & has a number as a payload return state + action.payload; default: return state; } } ``` 如上所示,**TypeScript** 根據 `type` 屬性推斷操作的類型,因此您無需檢查 `payload` 是否存在。 ## 2. 字串類型 通常你需要一個變數的特定值,這就是**文字類型**派上用場的地方。 ``` type Status = "idle" | "loading" | "success" | "error"; ``` 它也適用於數字: ``` type Review = 1 | 2 | 3 | 4 | 5; // or better yet: const reviewMap = { terrible: 1, average: 2, good: 3, great: 4, incredible: 5, } as const; // This will generate the same type as above, // but it's much more maintainable type Review = typeof reviewMap[keyof typeof reviewMap]; ``` ## 3.類型守衛 **類型保護** 是另一種縮小變數類型的方法: ``` function isNumber(value: any): value is number { return typeof value === "number"; } const validateAge = (age: any) => { if (isNumber(age)) { // validation logic // ... } else { console.error("The age must be a number"); } }; ``` 注意:在上面的示例中,最好使用: ``` const validateAge = (age: number) => { // ... }; ``` 這個例子是為了展示 **type guards** 是如何工作的一個簡化。 ## 4.索引簽名 當對像中有**動態鍵**時,可以使用**索引簽名**來定義其類型: ``` enum PaticipationStatus { Joined = "JOINED", Left = "LEFT", Pending = "PENDING", } interface ParticipantData { [id: string]: PaticipationStatus; } const participants: ParticipantData = { id1: PaticipationStatus.Joined, id2: PaticipationStatus.Left, id3: PaticipationStatus.Pending, // ... }; ``` ## 5.泛型 **泛型** 是一個強大的工具,可以讓您的程式碼更易於重用。它允許您**定義一個類型,該類型將由您的函數的使用決定**。 在以下示例中,`T` 是通用類型: ``` const clone = <T>(object: T) => { const clonedObject: T = JSON.parse(JSON.stringify(object)); return clonedObject; }; const obj = { a: 1, b: { c: 3, }, }; const obj2 = clone(obj); ``` ## 6. 不可變類型 您可以通過加入 `as const` 使您的類型**不可變**。這確保您不會意外更改值。 ``` const ErrorMessages = { InvalidEmail: "Invalid email", InvalidPassword: "Invalid password", // ... } as const; // This will throw an error ErrorMessages.InvalidEmail = "New error message"; ``` ## 7. 部分、選擇、省略和必需類型 通常在使用 **server** 和 **local data** 時,您需要將一些屬性設置為 **optional** 或 **required**。 而不是使用相同資料的略微更改版本定義數百個接口。您可以使用 `Partial`、`Pick`、`Omit` 和 `Required` 類型來做到這一點。 ``` interface User { name: string; age?: number; email: string; } type PartialUser = Partial<User>; type PickUser = Pick<User, "name" | "age">; type OmitUser = Omit<User, "age">; type RequiredUser = Required<User>; // PartialUser is equivalent to: // interface PartialUser { // name?: string; // age?: number; // email?: string; // } // PickUser is equivalent to: // interface PickUser { // name: string; // age?: number; // } // OmitUser is equivalent to: // interface OmitUser { // name: string; // email: string; // } // RequiredUser is equivalent to: // interface RequiredUser { // name: string; // age: number; // email: string; // } ``` 當然,你可以使用 **intersection** 來組合它們: ``` type A = B & C; ``` 其中 `B` 和 `C` 是任何類型。 --- 謝謝閱讀,希望對您有幫助!

給軟體工程師:50 個好用的 ChatGPT 咒語指令

下列 ChatGPT-4 咒語,對開發者很有幫助。附上原文與中文指令,供您參考。 原文出處:https://dev.to/hackertab_org/50-chat-gpt-prompts-every-software-developer-should-know-tested-9al ### **程式碼生成** - Generate a boilerplate `[language]` code for a `[class/module/component]` named [name] with the following functionality: `[functionality description].` - 為名為 [name] 的 `[class/module/component]` 生成樣板 `[language]` 程式碼,具有以下功能:`[functionality description]。 - Create a [language] function to perform `[operation]` on `[data structure]` with the following inputs: [input variables] and expected output: `[output description]`. - 建立一個 [語言] 函數以使用以下輸入對 `[資料結構]` 執行 `[操作]`:[輸入變數] 和預期輸出:`[輸出描述]`。 - Generate a `[language]` class for a `[domain]` application that includes methods for `[methods list]` and properties `[properties list]`. - 為包含“[方法列表]”的方法和屬性“[屬性列表]”的“[域]”應用程式生成一個“[語言]”類。 - Based on the [design pattern], create a code snippet in [language] that demonstrates its implementation for a [use case]. - 基於[設計模式],用[語言]建立一個程式碼片段,演示其對[用例]的實現。 **例子:** ``` Generate a boilerplate Python code for a shopping cart module named "ShoppingCart" with the following functionality: - A constructor that initializes an empty list to store cart items. - A method called "add_item" that takes in an item object and adds it to the cart. - A method called "remove_item" that takes in an item object and removes it from the cart if it exists. - A method called "get_items" that returns the list of items in the cart. - A method called "get_total" that calculates and returns the total price of all items in the cart. ``` ### **程式碼完成** - In `[language]`, complete the following code snippet that initializes a [data structure] with `[values]`: `[code snippet]`. - 在“[語言]”中,完成以下使用“[值]”初始化[資料結構]的程式碼片段:“[程式碼片段]”。 - Finish the `[language]` function that calculates [desired output] given the following input parameters: `[function signature]`. - 在給定以下輸入參數的情況下完成計算[期望輸出]的[語言]函數:[函數簽名]。 - Complete the `[language]` code to make an API call to `[API endpoint]` with [parameters] and process the response: `[code snippet]`. - 完成“[語言]”程式碼以使用[參數]對“[API 端點]”進行 API 呼叫並處理響應:“[程式碼片段]”。 **Example** : Finish the Python function that calculates the average of a list of numbers given the following input parameters: **示例**:完成計算給定以下輸入參數的數字列表的平均值的 Python 函數: ``` def calculate_average(num_list) ``` ### **錯誤檢測** - Identify any potential bugs in the following [language] code snippet: `[code snippet]`. - 確定以下 [語言] 程式碼片段中的任何潛在錯誤:`[程式碼片段]`。 - Analyze the given [language] code and suggest improvements to prevent [error type]: `[code snippet]`. - 分析給定的[語言]程式碼並提出改進建議以防止[錯誤類型]:`[程式碼片段]`。 - Find any memory leaks in the following [language] code and suggest fixes: `[code snippet]`. - 在以下 [語言] 程式碼中查找任何內存洩漏並提出修復建議:`[程式碼片段]`。 **Example** : Identify any potential bugs in the following Python code snippet: **示例**:辨識以下 Python 程式碼片段中的任何潛在錯誤: ``` def calculate_sum(num_list): sum = 0 for i in range(len(num_list)): sum += num_list[i] return sum ``` ### **程式碼審查** - Review the following `[language]` code for best practices and suggest improvements: `[code snippet]`. - 查看以下“[語言]”程式碼以獲得最佳實踐並提出改進建議:“[程式碼片段]”。 - Analyze the given `[language]` code for adherence to `[coding style guidelines]`: `[code snippet]`. - 分析給定的“[語言]”程式碼是否符合“[編碼風格指南]”:“[程式碼片段]”。 - Check the following [language] code for proper error handling and suggest enhancements: `[code snippet]`. - 檢查以下 [語言] 程式碼以正確處理錯誤並提出改進建議:`[程式碼片段]`。 - Evaluate the modularity and maintainability of the given `[language]` code: `[code snippet]`. - 評估給定“[語言]”程式碼的模塊化和可維護性:“[程式碼片段]”。 **Example** : Review the following Python code for best practices and suggest improvements: **示例**:查看以下 Python 程式碼以獲得最佳實踐並提出改進建議: ``` def multiply_list(lst): result = 1 for num in lst: result *= num return result ``` ### **API 文件生成** - Generate API documentation for the following `[language]` code: `[code snippet]`. - 為以下“[語言]”程式碼生成 API 文件:“[程式碼片段]”。 - Create a concise API reference for the given `[language]` class: `[code snippet]`. - 為給定的“[語言]”類建立簡明的 API 參考:“[程式碼片段]”。 - Generate usage examples for the following `[language]` API: `[code snippet]`. - 為以下“[語言]”API 生成用法示例:“[程式碼片段]”。 **Example** : Generate API documentation for the following JavaScript code: **示例**:為以下 JavaScript 程式碼生成 API 文件: ``` /** * Returns the sum of two numbers. * @param {number} a - The first number to add. * @param {number} b - The second number to add. * @returns {number} The sum of a and b. */ function sum(a, b) { return a + b; } ``` ### **查詢優化** - Optimize the following SQL query for better performance: `[SQL query]`. - 優化以下 SQL 查詢以獲得更好的性能:`[SQL 查詢]`。 - Analyze the given SQL query for any potential bottlenecks: `[SQL query]`. - 分析給定的 SQL 查詢是否存在任何潛在瓶頸:`[SQL 查詢]`。 - Suggest indexing strategies for the following SQL query: `[SQL query]`. - 為以下 SQL 查詢建議索引策略:`[SQL 查詢]`。 - Optimize the following NoSQL query for better performance and resource usage: `[NoSQL query]`. - 優化以下 NoSQL 查詢以獲得更好的性能和資源使用:`[NoSQL 查詢]`。 **Example** : Optimize the following SQL query for better performance: **示例**:優化以下 SQL 查詢以獲得更好的性能: ``` SELECT * FROM orders WHERE order_date BETWEEN '2022-01-01' AND '2022-12-31' ORDER BY order_date DESC LIMIT 100; ``` ### **用戶界面設計** - Generate a UI mockup for a `[web/mobile]` application that focuses on [`user goal or task]`. - 為專注於 [`用戶目標或任務]` 的`[web/mobile]` 應用程式生成 UI 模型。 - Suggest improvements to the existing user interface of `[app or website]` to enhance `[usability, accessibility, or aesthetics]`. - 建議改進“[應用程式或網站]”的現有用戶界面,以增強“[可用性、可存取性或美學]”。 - Design a responsive user interface for a `[web/mobile]` app that adapts to different screen sizes and orientations. - 為適應不同螢幕尺寸和方向的“[web/mobile]”應用程式設計響應式用戶界面。 **Example** : Generate a UI mockup for a mobile application that focuses on managing personal finances. **示例**:為專注於管理個人財務的移動應用程式生成 UI 模型。 ### **自動化測試** - Generate test cases for the following [language] function based on the input parameters and expected output: `[function signature]`. - 根據輸入參數和預期輸出為以下 [語言] 函數生成測試用例:`[函數簽名]`。 - Create a test script for the given [language] code that covers [unit/integration/system] testing: `[code snippet]`. - 為涵蓋[單元/集成/系統]測試的給定[語言]程式碼建立測試腳本:`[程式碼片段]`。 - Generate test data for the following [language] function that tests various edge cases: `[function signature]`. - 為以下測試各種邊緣情況的[語言]函數生成測試資料:`[函數簽名]`。 - Design a testing strategy for a [web/mobile] app that includes [unit, integration, system, and/or performance] testing. - 為 [網絡/移動] 應用程式設計測試策略,包括 [單元、集成、系統和/或性能] 測試。 **Example:** Generate test cases for the following Python function based on the input parameters and expected output: **示例:** 根據輸入參數和預期輸出為以下 Python 函數生成測試用例: ``` def divide(a: float, b: float) -> float: if b == 0: raise ZeroDivisionError('division by zero') return a / b ``` ### **程式碼重構** - Suggest refactoring improvements for the following [language] code to enhance readability and maintainability: `[code snippet]`. - 建議對以下 [語言] 程式碼進行重構改進,以增強可讀性和可維護性:`[程式碼片段]`。 - Identify opportunities to apply [design pattern] in the given [language] code: `[code snippet]`. - 確定在給定的[語言]程式碼中應用[設計模式]的機會:`[程式碼片段]`。 - Optimize the following [language] code for better performance: `[code snippet]`. - 優化以下 [語言] 程式碼以獲得更好的性能:`[程式碼片段]`。 **Example** : Optimize the following Python code for better performance: **示例**:優化以下 Python 程式碼以獲得更好的性能: ``` def find_max(numbers): max_num = numbers[0] for num in numbers: if num > max_num: max_num = num return max_num ``` ### **設計模式建議** - Based on the given [language] code, recommend a suitable design pattern to improve its structure: `[code snippet]`. - 根據給定的[語言]程式碼,推薦合適的設計模式來改進其結構:`[程式碼片段]`。 - Identify opportunities to apply the [design pattern] in the following [language] codebase: `[repository URL or codebase description]`. - 確定在以下 [語言] 程式碼庫中應用 [設計模式] 的機會:`[存儲庫 URL 或程式碼庫描述]`。 - Suggest an alternative design pattern for the given [language] code that may provide additional benefits: `[code snippet]`. - 為可能提供額外好處的給定 [語言] 程式碼建議替代設計模式:`[程式碼片段]`。 **Example:** Based on the given Python code, recommend a suitable design pattern to improve its structure: **例子:** 根據給定的Python程式碼,推薦合適的設計模式來改進其結構: ``` class TotalPriceCalculator: def calculate_total(self, items): pass class NormalTotalPriceCalculator(TotalPriceCalculator): def calculate_total(self, items): total = 0 for item in items: total += item.price * item.quantity return total class DiscountedTotalPriceCalculator(TotalPriceCalculator): def calculate_total(self, items): total = 0 for item in items: total += item.price * item.quantity * 0.9 # apply 10% discount return total class Order: def __init__ (self, items, total_price_calculator): self.items = items self.total_price_calculator = total_price_calculator def calculate_total(self): return self.total_price_calculator.calculate_total(self.items) class Item: def __init__ (self, name, price, quantity): self.name = name self.price = price self.quantity = quantity ``` ### **算法開發** - Suggest an optimal algorithm to solve the following problem: `[problem description]`. - 建議解決以下問題的最佳算法:`[問題描述]`。 - Improve the efficiency of the given algorithm for `[specific use case]`: `[algorithm or pseudocode]`. - 為“[特定用例]”提高給定算法的效率:“[算法或偽程式碼]”。 - Design an algorithm that can handle `[large-scale data or high-throughput]` for `[specific task or operation]`. - 為“[特定任務或操作]”設計一種可以處理“[大規模資料或高吞吐量]”的算法。 - Propose a parallel or distributed version of the following algorithm to improve performance: `[algorithm or pseudocode]`. - 提出以下算法的並行或分佈式版本以提高性能:`[算法或偽程式碼]`。 ### **程式碼翻譯** - Translate the following `[source language]` code to `[target language]`: `[code snippet]`. - 將以下“[源語言]”程式碼翻譯成“[目標語言]”:“[程式碼片段]”。 - Convert the given `[source language]` class or module to `[target language]` while preserving its functionality and structure: `[code snippet]`. - 將給定的“[源語言]”類或模塊轉換為“[目標語言]”,同時保留其功能和結構:“[程式碼片段]”。 - Migrate the following `[source language]` code that uses `[library or framework]` to [target language] with a similar library or framework: `[code snippet]`. - 將以下使用“[庫或框架]”的“[源語言]”程式碼遷移到具有類似庫或框架的“目標語言”:“[程式碼片段]”。 **Example:** Translate the following Python code to JavaScript: **示例:**將以下 Python 程式碼轉換為 JavaScript: ``` def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) ``` ### **個性化學習** - Curate a list of resources to learn `[programming language or technology]` based on my current skill level: `[beginner/intermediate/advanced]`. - 根據我目前的技能水平,策劃學習`[編程語言或技術]`的資源列表:`[初學者/中級/高級]`。 - Recommend a learning path to become proficient in `[specific programming domain or technology]` considering my background in `[existing skills or experience]`. - 考慮到我在“[現有技能或經驗]”方面的背景,推薦精通“[特定編程領域或技術]”的學習路徑。 - Suggest project ideas or coding exercises to practice and improve my skills in `[programming language or technology]`. - 建議專案想法或編碼練習,以練習和提高我在“[編程語言或技術]”方面的技能。 ### **程式碼可視化** - Generate a UML diagram for the following `[language]` code: `[code snippet]`. - 為以下“[語言]”程式碼生成一個 UML 圖:“[程式碼片段]”。 - Create a flowchart or visual representation of the given `[language]` algorithm: `[algorithm or pseudocode]`. - 建立給定“[語言]”算法的流程圖或可視化表示:“[算法或偽程式碼]”。 - Visualize the call graph or dependencies of the following `[language]` code: `[code snippet]`. - 可視化以下“[語言]”程式碼的呼叫圖或依賴關係:“[程式碼片段]”。 **Example** : Generate a UML diagram for the following Java code: **示例**:為以下 Java 程式碼生成 UML 圖: ``` public abstract class Vehicle { private String model; public Vehicle(String model) { this.model = model; } public String getModel() { return model; } public abstract void start(); public abstract void stop(); } public class Car extends Vehicle { public Car(String model) { super(model); } @Override public void start() { System.out.println("Starting car engine"); } @Override public void stop() { System.out.println("Stopping car engine"); } } public class Motorcycle extends Vehicle { public Motorcycle(String model) { super(model); } @Override public void start() { System.out.println("Starting motorcycle engine"); } @Override public void stop() { System.out.println("Stopping motorcycle engine"); } } ``` ### **資料可視化** - Generate a bar chart that represents the following data: `[data or dataset description]`. - 生成代表以下資料的條形圖:`[資料或資料集描述]`。 - Create a line chart that visualizes the trend in the following time series data: `[data or dataset description]`. - 建立一個折線圖,將以下時間序列資料的趨勢可視化:`[資料或資料集描述]`。 - Design a heatmap that represents the correlation between the following variables: `[variable list]`. - 設計一個表示以下變數之間相關性的熱圖:`[變數列表]`。 --- 以上,簡單分享,希望對您有幫助!

Git 入門上手教材:第1課 ── 學會 git 初始化

## 課程目標 - 學會 git 初始化 ## 課程內容 這次的課程,主要是透過每課作業練習實務情境 關於 git 的基本安裝,網路上有非常多教學,請根據你的作業系統,自己找一套安裝方法 不論是使用「終端機」讓你輸入指令,或者是有 GUI(圖形化介面)讓你點擊 UI 執行指令,都可以 關於 git 的基本觀念,學起來可深可淺,我只會簡單說明工作上需要的觀念 覺得黑箱或者想深入研究的話,可以上網搜尋相關關鍵字,深入理解 git 底層機制 --- 在要使用 git 追蹤的資料夾內,首先要使用的指令是 ``` git init ``` 這會初始化資料夾環境,讓 git 開始追蹤資料夾內所有檔案變化的一舉一動 其實不用想得太神奇,這指令只是在資料夾內建立一個隱藏的資料夾 `.git/` 而已(你可以根據你的作業系統,想辦法找到這個隱藏的資料夾) 後續的 git 指令,背後都是去查看 `.git/` 的內容而已 --- 初次使用 git,打指令可能會被要求設定名稱信箱,這些要用來記錄在 git 歷史訊息內,辨識操作者 ``` git config --global user.name "您的名稱" git config --global user.email "您的信箱" ``` --- 接著來試用兩個指令 首先是查看目前的工作狀態 ``` git status ``` 因為還沒有任何程式碼,所以應該會顯示「沒東西」的中文或英文訊息 接著來查看歷史編輯紀錄 ``` git log ``` 一樣會顯示「沒紀錄」的中文或英文訊息 這兩個基本指令,對於學習非常有幫助 在每次打任何 git 指令之前與之後,都打打看這兩個指令,可以幫助認識當前追蹤狀況 ## 課後作業 請開一個新資料夾,用 git 初始化這個資料夾 接著分別輸入 `git status` 與 `git log` 應該會看到 git 回應「沒東西」與「沒紀錄」的訊息 完成以上任務,你就完成這次的課程目標了! --- 交作業的方法: 可以把 `git status` 與 `git log` 顯示的文字內容複製,貼到留言區 也可以直接截圖視窗內 `git status` 與 `git log` 的內容,上傳到留言區

10 個可以改善開發體驗的 VSCode 外掛

- 原文出處:https://dev.to/j471n/vs-code-extensions-to-take-your-coding-to-the-next-level-50od ## Documatic 此外掛將 [Documatic](https://www.documatic.com/) 引入 VSCode:使用簡單查詢快速搜尋大型程式碼庫。 Documatic 使用 AI 連結您的查詢和程式碼片段之間的關係,因此您不必知道要查找的確切關鍵字! **⬇️** [**下載**](https://marketplace.visualstudio.com/items?itemName=Tyriar.sort-lines) ![](https://i.imgur.com/KYutr9T.gif) ## Sort lines 此外掛允許您按字母或數字快速對程式碼進行排序,從而在處理大文件時節省時間。當您有要排序的資料時,這會非常方便。 **⬇️** [**下載**](https://marketplace.visualstudio.com/items?itemName=Tyriar.sort-lines) ![使用動畫](https://github.com/Tyriar/vscode-sort-lines/raw/HEAD/images/usage-animation.gif) ## TabNine 此外掛使用 AI 提供程式碼自動完成建議,可以幫助您節省時間並提高程式碼品質。它支援很多語言和框架。但是要小心使用它,因為它會佔用你系統的很多資源。 **⬇️** [**下載**](https://marketplace.visualstudio.com/items?itemName=TabNine.tabnine-vscode) ![Tabnine 主要完成](https://raw.githubusercontent.com/codota/tabnine-vscode/master/assets/completions-main.gif) ## **Template String Converter** 可以在程式碼編輯器中鍵入“${”時將普通字串轉換為模板字串。 **⬇️** [**下載**](https://marketplace.visualstudio.com/items?itemName=meganrogge.template-string-converter) ![鍵入一個美元符號然後在字串中打開大括號將引號轉換為反引號](https://raw.githubusercontent.com/meganrogge/template-string-converter/master/images/demo.gif) ## **Error Lens** ErrorLens 增強了語言診斷功能,突出顯示語言生成診斷的整行,並連結相關訊息。 **⬇️** [**下載**](https://marketplace.visualstudio.com/items?itemName=usernamehw.errorlens) ![演示圖片](https://raw.githubusercontent.com/usernamehw/vscode-error-lens/master/img/demo.png) ## **WakaTime** [WakaTime](https://wakatime.com/vs-code) 是一個開源 VS Code 外掛,用於從您的寫程式工時中,自動生成指標、分析和時間追蹤。 **⬇️** [**下載**](https://marketplace.visualstudio.com/items?itemName=WakaTime.vscode-wakatime) ![專案概覽](https://wakatime.com/static/img/ScreenShots/Screen-Shot-2016-03-21.png) ## **Chat** 通過使用此外掛,您可以在 VS Code 中與您的 Slack 和 Discord 團隊聊天。 * **安靜的通知**:聊天應用程式可能會讓人分心。此外掛使聊天變得有用、上下文相關且不會分散注意力。 * **豐富的格式**:分享 Markdown 程式碼片段,並在您的聊天訊息中加入表情符號。 * **本地外觀**:在您喜歡的主題和網格編輯器佈局中使用聊天。 **⬇️** [**下載**](https://marketplace.visualstudio.com/items?itemName=karigari.chat) ![截圖](https://raw.githubusercontent.com/karigari/vscode-chat/master/readme/Live%20Share%20Chat.gif) ## **SVG Preview** 允許您直接在 VS 程式碼中查看 SVG 文件。如果您在 vs 程式碼中打開 SVG 文件,那麼預設情況下它會顯示 SVG 程式碼。使用它後,您可以看到 SVG 的預覽。 **⬇️** [**下載**](https://marketplace.visualstudio.com/items?itemName=SimonSiefke.svg-preview) ![演示](https://github.com/SimonSiefke/vscode-svg-preview/raw/master/demo_images/demo.gif) ## **Headwind** Headwind 是用於 Visual Studio Code 的 Tailwind CSS 類排序器。它通過解析您的程式碼並重新打印類別標籤來強制執行一致的類別排序。 **⬇️** [**下載**](https://marketplace.visualstudio.com/items?itemName=heybourn.headwind) ![解釋器](https://github.com/heybourn/headwind/blob/master/img/explainer.gif?raw=true) ## **Material Design Palette Generator** [Material Design Palette Generator](https://marketplace.visualstudio.com/items?itemName=piyush-bhatt.vscode-mat-palette) 是一個 VSCode 外掛,用於生成 [material 調色板](https://material.io/design/color/the-color-system.html#tools-for-picking-colors)。 **⬇️** [**下載**](https://marketplace.visualstudio.com/items?itemName=piyush-bhatt.vscode-mat-palette) ![獲取從給定的十六進制顏色生成的完整調色板](https://raw.githubusercontent.com/piyush-bhatt/vscode-mat-palette/master/assets/readme/Primary.gif) --- 以上,簡單分享,希望對您有幫助!

使用 Tailwind 開發時,適合搭配的 4 款 VSCode 外掛

這些外掛都在這個 VSCode 外掛包裡面 [TailwindCSS Kit](https://marketplace.visualstudio.com/items?itemName=KalimahApps.tailwindcss-kit) 原文出處:https://dev.to/kalimahapps/4-vscode-extensions-i-use-for-tailwind-2him ## 1. [Tailwind CSS IntelliSense](https://marketplace.visualstudio.com/items?itemName=bradlc.vscode-tailwindcss) ![tailwind css 智能圖像](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4w36g7owmtrmljbesu24.png) Tailwind CSS IntelliSense 是一個強大的工具,可以幫助開發人員更快、更高效地編寫程式碼。它為 Tailwind CSS 類別提供即時建議,減少錯誤並提高程式碼品質。使用 IntelliSense,開發人員可以提高工作效率、縮短學習曲線並改進應用程式的可存取性。如果您是使用 Tailwind CSS 的開發人員,一定要試試這個強大的外掛。 ## 2. [Tailwind Fold](https://marketplace.visualstudio.com/items?itemName=stivo.tailwind-fold) ![tailwind 折疊擴展圖像](https://github.com/stivoat/tailwind-fold/raw/HEAD/images/docs/demo.gif) 在使用 Tailwind 時,此外掛非常有用。長長的類列表會使 html 有點混亂,此外掛提供了一種隱藏它們並僅在需要時顯示的好方法。除了預設功能外,這些選項經過細心設計,幾乎可以滿足任何偏好。例如,我喜歡在點擊線條而不是類別本身時展開類別。 ## 3. [Tailwind Documentation](https://marketplace.visualstudio.com/items?itemName=alfredbirk.tailwind-documentation) ![Tailwind 文件圖片](https://user-images.githubusercontent.com/11172530/163716626-8d74a1bb-f05b-4b45-aa12-70f66e0efad8.gif) Tailwind Documentation 提供對官方 Tailwind CSS 文件的快速存取。此外掛使開發人員能夠直接從 VSCode 編輯器中存取 Tailwind CSS 文件,而無需打開瀏覽器或離開編輯器。 ## 4. [Tailwind Config Viewer](https://marketplace.visualstudio.com/items?itemName=KalimahApps.tailwind-config-viewer) ![Tailwind 配置查看器圖像](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zxwuaxi8v4o9olb4g06d.png) Tailwind 配置可能會令人困惑。它們可能呈指數級增長,並使用戶更難了解已解析的設定。這外掛使用戶能夠查看 **resolved** Tailwind 配置,它還會顯示任何與顏色相關的類別(text-\*、bg-\*、accent-\* ... 等)的顏色 --- 以上,簡單分享,希望對您有幫助!

# JS油猴系列-遮蔽廣告(D卡未登入)腳本、自定義新增名單

## 前情提要 逛論壇或網站常常有惱人的蓋板廣告,要馬就是要你登入、註冊, 要馬就是搞一堆課程的販售廣告, 對重視使用者體驗的人來說,真的是一場噩夢! 為了解決這個問題,我模擬了AdBlock的其中一個功能,刪除頁面上的元素! 乾乾淨淨才是王道阿。 ## 效果 按下ctrl+Q啟動刪除元素模式: ![](https://i.imgur.com/411nh3Q.png) 被選取的會加上邊框色彩,讓人確認是否要刪除: ![](https://i.imgur.com/zPEKMhC.png) 點選確認後: ![](https://i.imgur.com/nnOY4Ji.png) 煩人的元素就此消失在這個永恆的宇宙裡。 ## 觀念筆記 ### 套件一:toastr ```javascript= //toast.js cdn匯入 const toastJS = ` <link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.min.js"></script>` $('body').append(toastJS); ``` ![](https://i.imgur.com/lNDch3V.png) [測試效果反應網站](https://codeseven.github.io/toastr/demo.html) ![](https://i.imgur.com/v95GUfO.png) [[十分鐘學習] toastr - 簡易提示訊息](https://ithelp.ithome.com.tw/articles/10197861) ### 套件二:SweetAlert2 ```javascript= //設定cdn使用Sweetalert套件 let Sweetalert2=`<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>` $('html').append(Sweetalert2) ``` ![](https://i.imgur.com/qUeTUlj.png) ![](https://i.imgur.com/FJH8EMX.png) 有提供很多API範例,還可以自己定義可愛的小動物XD [官方網站](https://sweetalert2.github.io/) ### 監聽鍵盤組合鍵 ``` document.addEventListener('keydown', function(e){ if(e.which==81 && e.ctrlKey==true){ //..... } ``` ### Object.assign 動態修改樣式 ![](https://i.imgur.com/AzZMRCc.png) [用JS動態修改CSS的三種寫法,花式JS玩弄樣式,嚇死你的同事!](https://codelove.tw/@JsLover0018/post/Ja64Kx) ## 油猴程式碼 ```javascript= // ==UserScript== // @name 刪除廣告元素 // @namespace http://tampermonkey.net/ // @version 0.1 // @description try to take over the world! // @author You // @match *://*/* // @require https://code.jquery.com/jquery-3.6.3.min.js // @icon https://www.hexschool.com/ // @grant none // ==/UserScript== (function() { //--------------------------------------- // 宣告變數 let set let Check = true; let List=[] //設定選取的border色彩效果 let styleNeon = `@keyframes neon-color { from { filter: hue-rotate(0deg); } to { filter: hue-rotate(360deg); } }` $('style:last').append(styleNeon) //設定cdn使用Sweetalert套件 let Sweetalert2=`<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>` $('html').append(Sweetalert2) //使用者點選某個元素 執行刪除元素function function SetDeleteEl(e){ e.preventDefault(); set=e.target.class console.log(set) const border={ border:"4px dotted red" } const Neon={ animation: "neon-color 2.5s linear infinite" } const NoBorder={ border:"none" } const StopNeon={ animation: "" } Object.assign(e.target.style,border) Object.assign(e.target.style,Neon) //e.target.remove() if (Check==true){ Swal.fire({ title: '確定要刪除這個元素?', showDenyButton: true, showCancelButton: false, confirmButtonText: '確認', denyButtonText: `取消`, }).then((result) => { /* Read more about isConfirmed, isDenied below */ if (result.isConfirmed) { e.target.remove() List.push(e.target.className) localStorage.setItem('List',List); Check=false; Swal.fire('成功刪除此元素!', '', 'success') } else if (result.isDenied) { Check=false; Swal.fire('動作已取消', '', 'info') Object.assign(e.target.style,NoBorder) Object.assign(e.target.style,StopNeon) }; }); } //選取流程結束後 解開選取流程的事件綁定 $('body').unbind('click',SetDeleteEl) } //toast.js cdn匯入 const toastJS = ` <link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.1.4/toastr.min.js"></script>` $('body').append(toastJS); // 當使用者按下Ctrl+Q 就執行主程序 document.addEventListener('keydown', function(e){ if(e.which==81 && e.ctrlKey==true){ RemoveListItem(); toastr.options = { // 參數設定[註1] "closeButton": false, // 顯示關閉按鈕 "debug": false, // 除錯 "newestOnTop": false, // 最新一筆顯示在最上面 "progressBar": false, // 顯示隱藏時間進度條 "positionClass": "toast-bottom-right", "preventDuplicates": false, // 隱藏重覆訊息 "onclick": null, // 當點選提示訊息時,則執行此函式 "showDuration": "300", // 顯示時間(單位: 毫秒) "hideDuration": "1000", // 隱藏時間(單位: 毫秒) "timeOut": "2000", // 當超過此設定時間時,則隱藏提示訊息(單位: 毫秒) "extendedTimeOut": "1000", // 當使用者觸碰到提示訊息時,離開後超過此設定時間則隱藏提示訊息(單位: 毫秒) "showEasing": "swing", // 顯示動畫時間曲線 "hideEasing": "linear", // 隱藏動畫時間曲線 "showMethod": "fadeIn", // 顯示動畫效果 "hideMethod": "fadeOut" // 隱藏動畫效果 } toastr.success( "已開啟刪除元素模式!" ); $('body').on('click',SetDeleteEl) Check=true }}) function RemoveListItem(){ if (localStorage.getItem('List')!=null){ item=localStorage.getItem('List').split(',') for (i=0;i<item.length;i++){ item[i]='.'+item[i] item[i]=item[i].replaceAll(' ','.') try{ document.querySelector(item[i]).remove()} catch{} } // item='.'+item // item=item.replaceAll(' ','.') // document.querySelector(item).remove() } } //-------------------------------------------------------- })(); ``` ## 心得 短短150行左右的程式碼,就寫得好辛苦!(汗 過去寫過很多次類似的東西,所以基本上沒有卡關的地方, 只是設計邏輯、嘗試的過程還是比想像的還要耗精神( ´•̥̥̥ω•̥̥̥ ) 但寫出來比過去快很多,也比過去好看超級多的。 給自己一個讚讚! 重新把localstorge複習一遍,Object.assign、套件使用等。 算是一個確確實實的實力鞏固過程。 ## 延伸 未來可以新增控制黑名單元素的UI。 可以新增、刪除,看有哪些元素被列入要刪除的黑名單。

在 React 裡面,關於 Strict Mode 的簡單說明

`React.StrictMode` 是一個好用的元件,用於突出顯示應用程式中的潛在問題。就像 `<Fragment>` 一樣,`<StrictMode>` 不會渲染任何額外的 DOM 元素。在這篇文章中,我們將深入探討什麼是嚴格模式、它是如何運作的,以及為什麼你應該考慮使用看看。 原文出處:https://dev.to/codeofrelevancy/what-is-strict-mode-in-react-3p5b --- ## 什麼是 React 中的嚴格模式? 嚴格模式是一組開發工具,可幫助您在程式碼中找到潛在問題。當您在 React 應用程式中啟用嚴格模式時,您實際上是在告訴 React 打開一堆額外的檢查👀 和警告,以便幫助您寫出更好的程式碼。這些檢查和警告可以捕獲以下內容: 1. 有副作用的元件 2. 已棄用或不安全的生命週期方法 3. 某些內置函數的不安全用法 4. 列表中的重複鍵 ![嚴格模式](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/10tfwojwoyip5ld20yec.gif) --- ## 啟用嚴格模式 在 React 應用程式中啟用嚴格模式非常簡單。您可以通過在主 `index.js` 文件中加入一行程式碼來實現: ``` import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); ``` ## 為應用程式的一部分啟用嚴格模式 您還可以為應用程式的任何部分啟用嚴格模式: ``` import { StrictMode } from 'react'; function App() { return ( <> <Header /> <StrictMode> <main> <Sidebar /> <Content /> </main> </StrictMode> <Footer /> </> ); } ``` 在這種情況下,嚴格模式檢查不會針對“頁首”和“頁腳”元件執行。但是,它們將在 `Sidebar` 和 `Content` 以及它們內部的所有元件上執行,無論它有多深層。 --- ## 嚴格模式只影響開發環境 請務必注意,嚴格模式對 React 應用程式的正式環境建置沒有影響。嚴格模式啟用的任何檢查或警告都不會出現在用戶看到的應用程式最終版本中。除此之外,嚴格模式會打開額外的檢查和警告,它可能會減慢您的開發環境速度。 ![嚴格模式只影響開發環境](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nu5kpm4ixxfesjdhv1cv.gif) --- ## 嚴格模式可以幫助你捕捉細微的錯誤 有時 React 應用程式中的錯誤可能很難追踪,特別是諸如 race conditions 或對元件狀態的不正確假設等細微問題。啟用嚴格模式的額外檢查和警告,您可以在這些錯誤導致嚴重問題之前發現它們。 --- ## 嚴格模式可以幫助您了解最新的最佳實踐 React 是一個快速發展的框架,最佳實踐會隨著時間而改變。啟用嚴格模式並留意它提供的警告和建議,您可以確保您的 React 程式碼遵循當前的最佳實踐。例如在渲染列表時使用 key 屬性,或者在 render() 中避免副作用。 --- ## 儘早發現潛在問題 嚴格模式可以在您的程式碼中發現可能在未來引起的問題,以免它們成為嚴重問題。比方說,它可以檢測並警告已棄用的生命週期方法以及對不再推薦的 [findDOMNode()](https://react.dev/reference/react-dom/findDOMNode) 的存取。 ![findDOMNode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/awx9dnh9eexg4eb73wt2.png) ![findDOMNode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i5hjs6oae3lj38mbhjwk.png) --- ## 防止常見錯誤 啟用嚴格模式,您可以避免一些隱晦的常見錯誤,例如:直接修改狀態而不是使用 setState()、使用未宣告變數。 --- ## 辨識不安全的生命週期 React Strict Mode 可以幫助辨識元件中不安全生命週期方法的使用。例如,它可以警告您使用 `componentWillUpdate` 和 `componentWillReceiveProps` 方法,這兩種方法都被認為是不安全的,將在 React 的未來版本中被刪除。 ![不安全生命週期](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s6d9qh4xjz16u9xlsle5.png) 假設您有一個元件,它使用 `componentWillReceiveProps()` 來根據傳入的 props 更新其狀態: ``` class BlackMamba extends React.Component { constructor(props) { super(props); this.state = { venom: props.venom }; } componentWillReceiveProps(nextProps) { this.setState({ venom: nextProps.venom }); } render() { return <div>{this.state.venom}</div>; } } ``` 在常規模式下,該元件會按預期工作,但在“React.StrictMode”下,您會在控制台中看到一條警告: > 警告:BlackMamba 使用 `componentWillReceiveProps`,這被認為是一種不安全的生命週期方法。請使用靜態的 getDerivedStateFromProps 。 --- ## 過時的字串引用 API 用法 嚴格模式還可以警告您過時的字串 `ref` API 的使用。該 API 已被官方棄用。您應該使用更安全、更易於使用的 `createRef` API。 ![過時的字串引用 API 用法](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gv8lf8ubk7vv4yg8m4qo.png) 比方說,您有一個元件使用這樣的字串引用: ``` import { Component } from "react"; import { createRoot } from "react-dom/client"; class BlackMamba extends Component { componentDidMount() { this.refs.venom.focus(); } render() { return ( <> <h1>Black Mamba</h1> <input ref="venom" /> </> ); } } const root = createRoot(document.getElementById("root")); root.render(<BlackMamba />); ``` 您不會在控制台中看到任何錯誤。 ![輸出](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/trxw9auusgunit73rvzp.png) 當您像這樣在您的應用中啟用“React.StrictMode”時: ``` import { StrictMode, Component } from "react"; import { createRoot } from "react-dom/client"; class BlackMamba extends Component { componentDidMount() { this.refs.venom.focus(); } render() { return ( <> <h1>Black Mamba</h1> <input ref="venom" /> </> ); } } const root = createRoot(document.getElementById("root")); root.render( <StrictMode> <BlackMamba /> </StrictMode> ); ``` 您會在控制台中看到如下所示的警告: > Warning: A string ref, "venom", has been found within a strict mode tree. String refs are a source of potential bugs and should be avoided. We recommend using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref ![輸出](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tnf0qdctk8q7q9d1mzf0.png) 讓我們用 `createRef` API 修復它: ``` import { StrictMode, Component, createRef } from "react"; import { createRoot } from "react-dom/client"; class BlackMamba extends Component { constructor(props) { super(props); this.venom = createRef(); } componentDidMount() { this.venom.current.focus(); } render() { return ( <> <h1>Black Mamba</h1> <input ref={this.venom} /> </> ); } } const root = createRoot(document.getElementById("root")); root.render( <StrictMode> <BlackMamba /> </StrictMode> ); ``` 修理完成! ![輸出](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0pq7w11m292b3sh9e3aj.png) --- ## 過時的 Context API [舊版 Context API](https://legacy.reactjs.org/docs/legacy-context.html) 在 React 中已棄用,已被新的 Context API 取代。 React Strict Mode 可以幫助您檢測過時的 Context API 的任何使用情況,並鼓勵您切換到 [新 API](https://react.dev/reference/react/useContext) ![檢測遺留上下文 API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iowjhzc795mngti4ayo0.png) --- 如果您還沒有使用嚴格模式,那絕對值得使用看看! 以上簡單分享,希望對您有幫助!

新手推薦:最基本的 10 個 Git 指令與原理

Git 是軟體工程師最重要的工具之一,今天來學一點 Git 吧! 原文出處:https://dev.to/swordheath/git-the-basic-commands-every-developer-should-know-2m1e **什麼是 Git?** Git 是一個追蹤文件變更的版本控制系統。使用 Git 可以讓您保留所有更改的記錄並根據需要返回到特定版本。它使用方法簡單,佔用空間小,而且非常高效。它的分支模型使它有別於幾乎所有其他可用的 SCM。您可以使用 GitHub 或其他線上主機來儲存文件的備份及其修訂歷史。 **Git 的主要元件** 對我來說,Git 是在團隊專案中使用的絕佳工具,因為它有助於避免程式碼混淆,並帶來一個簡單而有效的工作流程。 ** Repository** Git 存儲庫(或簡稱 repo)包含所有專案文件以及整個修訂歷史記錄。您使用一個普通的資料夾(例如網站的根目錄夾)並告訴 Git 將它變成一個存儲庫。這將建立一個 .git 子文件夾,其中儲存了所有用於追蹤修改的 Git 元資料。簡而言之,存儲庫是您保存程式碼的地方。 **Commit** 要向存儲庫加入新程式碼,您需要進行提交,這是存儲庫在特定時間點的快照、將特定更改或一系列更改提交到存儲庫中的文件。 Git 的歷史紀錄由連續的提交組成。 **Branch** 分支用於儲存您的更改,直到它們準備就緒。在主分支(master)保持穩定的情況下,您可以在分支上工作。完成後,您可以將其與母版合併。最大的好處是您可以在一個存儲庫中擁有多個分支,並在需要時合併它們。 **Pull requests** 這是 Git 中用於在將更改合併到您的程式碼庫之前討論更改的技術。PR 不僅僅是一個通知;它是針對所提議功能的專門討論串。這在多人處理同一份程式碼時特別方便,允許開發人員檢查彼此的工作。 現在我們已經簡要討論了 Git 的主要元件,我想列出每個開發人員在開始使用 Git 之前必須知道的**10 個基本 Git 命令**。 **1。開始一個新的存儲庫** ``` git init ``` **2。分別設定作者姓名和電子郵件地址以用於您的提交** ``` git config - - global user.name “[name]” git config - - global user.email “[email address]” ``` **3。從遠程存儲庫下載現有程式碼** ``` git clone <https://name-of-the-repository-link> ``` **4。建立一個新分支** ``` git branch <branch-name> ``` **5。在 master 中合併分支** ``` git merge <branch-name> ``` **6。從遠程存儲庫取得更新** ``` git pull <remote> ``` **7。將文件加入到 Git 的暫存區** ``` git add <file or directory name> ``` **8。存儲庫的當前狀態** ``` git status ``` **9。將在 master 分支上所做的更改發送到您的遠程存儲庫** ``` git push [variable name] master   ``` **10。更改 head(在版本歷史記錄中加入一筆更新)** ``` git commit -m " Commit Message" ``` --- 這些是每個使用 Git 的人都必須知道的主要指令。Git 非常好用,指令數量也相當多。但是記住這些指令並不是一項艱鉅的任務——您只需要開始使用 Git,大多數指令都會憑直覺記住。

寫了多年 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> ``` 以上分享,希望對您有幫助

請益-這樣子的coding遊戲是否能夠一人開發?會太具挑戰嗎?

## 前提 https://flexboxfroggy.com/ 類似這種遊戲或是https://hexschool.github.io/flexbox-pirate/index.html#/simple (六角應該是學習他  這兩個基本上一樣XD) 想問這種可以讓使用者丟code的遊戲 是否會很難開發 這邊順便提供相關遊戲 [10 amazing games to learn CSS](https://daily-dev-tips.com/posts/10-amazing-games-to-learn-css/) [10 games to learn JavaScript](https://dev.to/dailydevtips1/10-games-to-learn-javascript-155j) 有些難度似乎會比較高 是因為還要用美術素材 但我想 我若是使用人家現成的 純粹練習 這方面應該也不困難 ## 疑問 我在想 其實應該會算是個很有趣的挑戰? 我考慮的點  是要判斷user的code是否正確 基本上去判斷text area的內容有沒有 那些特定的條件 用判斷式去寫 應該不至於太難 想說試著練習寫一個這個遊戲 因為我看六角也是照著人家的做XD 不知道前輩們對這樣的練習有什麼建議~~ 會有什麼地方要注意嗎 感恩!!!!!!!! ## 想法漫談 從以前練到現在,真的很喜歡這個論壇~~~未來有機會搞一個自己設計的遊戲關卡 也可以讓大家練習JS 因為我看到有些練習的遊戲是要付費的 在這裡:https://codepip.com/games 想說我可以自己搞一個免費版 XDD 只是怕弄下去也許是一個太大的專案? 或者其實跟切版差不多 幾個小時就OK? 那我一定馬上來弄 感覺就超好玩~超酷~

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))) ``` --- 感謝閱讀✨!

[作業問題]HTML&CSS 第6課 Loading Page

您好,請問幾個問題。 1.為什麼我使用position:relative,網頁會出現很大的空白,我該如何解決。 2.使用絕對位置,我該如何讓我的網頁隨著比例縮放。 問題1 : ![](https://i.imgur.com/wzXvqGk.jpg) 問題2: ![](https://i.imgur.com/4a7OA6u.jpg) ![](https://i.imgur.com/BzUIBdJ.jpg) 這是網頁全開的時候 ![](https://i.imgur.com/YGNQAfx.jpg) HTML: ``` <!DOCTYPE html> <html> <head> <meta charset = "UTF-8"> <title>佳加安全帽</title> <link rel = "stylesheet" href = "style.css"> </head> <body class = "page"> <div class = "navbar"> <div class="container"> <div class = "logo"> <a href = "#"><img src = "jiajia.jpg"/></a> </div> <div class="menu"> <ul class="choose"> <li><a href = "">所有商品</a></li> <li><a href = "">特價商品</a></li> <li><a href = "">安全帽</a></li> <li><a href = "">藍芽耳機</a></li> <li><a href = "">裝備衣物</a></li> <li><a href = "">配件</a></li> <li><a href = "">包包</a></li> </ul> </div> <div class="user"> <ul> <li><a href = "">Log in 登入</a></li> <li>|</li> <li><a href = "">Sign up 註冊</a></li> </ul> </div> </div> </div> <div class="background"> <div class="content"> <h1>在危險的世界中,給你多一份安全</h1> </br> </br> <p>留下您的email,獲得新商品及最新優惠資訊</p> </br> <input type= "email" name = "email" value = "Your email"> </br> <input class="submit" type = "submit" name= "submit" value = "訂閱"> </div> </div> </body> </html> ``` CSS: ``` *{ margin: 0px; padding: 0px; list-style-type: none; text-decoration: none; } .navbar{ background-color: #272727; height: 50px; width: 100%; } .logo img{ height: 50px; } .menu{ position: relative; top: -50px; line-height: 45px; left: 500px; } .menu li{ float: left; } .menu a{ color: #D9B300; display: block; padding: 0 10px; } .menu a:hover{ background-color: #D9B300; color: #272727; } .user{ position: relative; top: -50px; left: 800px; line-height: 45px; } .user li{ float: left; color: #D9B300; } .user a{ color: #D9B300; display: block; padding: 0 10px; } .user a:hover{ background-color: #D9B300; color: #272727; } h1{ color: white; } p{ color: white; } .background{ background-image: url("motor.jpg"); background-size: cover; background-repeat: no-repeat; height: 660px; text-align: center; } .content input{ width: 400px; height: 40px; } .content h1{ font-size: 40px; } .content p{ font-size: 20px; } .content{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .submit{ font-weight: bold; font-size: 20px; background-color: #D9B300; color: #272727; border-radius: 10px; border: 0px; } .submit:hover{ background-color: #272727; color: #D9B300; }