Try   HackMD

Yarn + Vite + React + Typescript + tailwind 環境建置

Ubuntu yarn 安裝與環境設定

sudo apt update -y && sudo apt upgrade -y
sudo apt install nodejs npm -y
sudo corepack enable
corepack enable
sudo corepack prepare yarn@v3.5.0 --activate
corepack prepare yarn@v3.5.0 --activate
sudo npm install --global yarn # 全域安裝 yarn

如果遇到 PPA 查找錯誤導致無法 update 的議題 (與本次目標直接關聯),可進入
/etc/apt/sources.list.d 中刪除所有 PPA。

macOS yarn 環境設定

brew install node # node and npm
brew install yarn # yarn

建構軟體並設定開發環境

建構軟體模板

yarn create vite YOUR_APP --template react-ts
cd YOUR_APP

為本專案準備 v2 以後的 yarn 版本

比如 3.5.0

yarn set version stable
yarn --version # e.g. 3.5.0

以 yarn 初始化以 VSCode 開發之專案

yarn install
yarn dlx @yarnpkg/sdks vscode

注意,第二條命令必須在 yarn v2 以上才可運行,若遇到

Internal Error: This tool can only be used with projects using Yarn Plug'n'Play
...

的問題,請依照 yarn v2 的指示調整。

新增開發時使用之套件

基本觀念: npm 中以 @ 開頭之套件為有 scope 的套件。Scope 是為了給一群套件附上一個主標籤 (很像作用域、命名空間的意思),方便管理套件集合而出現的類別。

欲知詳情,可使用 npm help scope,官方提示即給出清楚的解釋。

# basic packages
yarn add --dev autoprefixer tailwindcss prettier postcss
# packages about eslint
yarn add --dev eslint eslint-config-prettier eslint-plugin-prettier
# Add scoped packages
yarn add --dev @typescript-eslint/eslint-plugin @typescript-eslint/parser @vitejs/plugin-react

啟用 VSCode 的各項輔助工具

自動安裝外掛

如果正確新增開發時使用之套件,yarn 會自動幫我們添加並設定好本檔案,但並不會有最後一個套件,不過我非常推薦使用。

新增 extensions.json,並加入以下內容,如此一來於任何電腦的 VSCode 中開啟本專案都會自動下載必要外掛。

{
  "recommendations": [
    "arcanis.vscode-zipfs",
    "dbaeumer.vscode-eslint",
    "esbenp.prettier-vscode",
    "rvest.vs-code-prettier-eslint"
  ]
}

啟用 ESlint 強化 IntelliSense

新增 .eslintrc 檔並加入客製化設定。比如以下此將會啟用 Typescript 的 ESlint 以及與 Prettier 外掛連動。同時規定 Typescript 中不允許有未使用之變數和顯式 any 變數。

{
    "extends": [
        "plugin:@typescript-eslint/recommended",
        "plugin:prettier/recommended"
    ],
    "plugins": [
        "@typescript-eslint", "prettier"
    ],
    "rules": {
        "no-console": "warn",
        "@typescript-eslint/no-unused-vars": "error",
        "@typescript-eslint/no-explicit-any": "error",
        "prettier/prettier": "error"
    }
}

Prettier 細節設定

新增 .prettierrc 檔並加入客製化設定,比如:

{
    "singleQuote": true,
    "semi": false
}

第一行表啟用單引號字串,第二行表允許無分號結尾。

難疑排解

yarn 任何抽搐行為

遇到 yarn 任何抽搐行為,走投無路時

  • 殺掉 yarn.lock (紀錄 package 版本鎖定的檔案)
  • yarn install 重新裝載套件

yarn 與 npm

由於我們使用 yarn (npm 的改良版) 而非 npm,雖然前者可識別後者,但反之不行,故避免使用 npm 指令進行套件管理操作。

yarn v2 (up) 與 yarn v1

yarn v2 中套件依賴的管理會以壓縮檔的形式存在 .yarn 資料夾下,不應該出現 node_module 資料夾。若有表示

  • 不小心用上 npm
    不要用 npm
  • yarn 版本過舊 (v1),則
    • yarn set version stable 切換至版本更新的 yarn
    • 確認 .yarnrc.yml 中沒有 nodeLinker: node-modules 這句 (表示 link 於 node_modules)
    • 照「yarn 任何抽搐行為」的指示繼續

其他瑣碎問題

  • 修改 Prettier 設定檔後重新載入 VSCode 頁面才會生效
  • 套件的加入不應直接編輯 package.json,應該使用 yarn add 命令完成