CAFECA-IO / iSunCoin-official

https://i-sun-coin-official.vercel.app
MIT License
0 stars 0 forks source link

Recreate a Next project using Pages Router #27

Closed godmmt closed 2 weeks ago

godmmt commented 2 weeks ago

此單為 https://github.com/CAFECA-IO/iSunCoin-official/issues/24 延伸

在本地端建立一個新的 Next 專案 (Note the folder name) 選擇 Pages Router

npx create-next-app . --ts
ESLint - Yes
Tailwind CSS - Yes
src directory - Yes
App Router - No
import alias (@/*) - No

並且走過一次 pre commit 的設定流程,可參考:

  1. https://github.com/CAFECA-IO/KnowledgeManagement/blob/master/survey/PreCommit.md
  2. https://github.com/CAFECA-IO/iSunCoin-official/issues/10

最後如果比較後 新專案比目前的專案好的話 就在目前的 repository 開一個新分支 把新專案推上來取代

godmmt commented 2 weeks ago

將所有輸入終端機的指令整理在這裡 將新增的檔案內容新增在這裡

整理一起在這裡:https://github.com/CAFECA-IO/iSunCoin-official/issues/27#issuecomment-2167610328

之後遇到專案要 pre commit 可以參考這裡的步驟

godmmt commented 2 weeks ago

走 pre commit 流程中遇到的問題記錄怎麼解 文件中有些地方可能需要更新 所以參考新專案一併記錄

所以超過一點時間

godmmt commented 2 weeks ago

現在在 流程的這一步 遇到 Error

liz at LMP in ~/Desktop/isuncoin (main) 
$ npm install @typescript-eslint/eslint-plugin@^6.0.0 --save-dev
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: isuncoin@0.1.0
npm ERR! Found: @typescript-eslint/parser@7.13.0
npm ERR! node_modules/@typescript-eslint/parser
npm ERR!   dev @typescript-eslint/parser@"^7.13.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer @typescript-eslint/parser@"^6.0.0 || ^6.0.0-alpha" from @typescript-eslint/eslint-plugin@6.21.0
npm ERR! node_modules/@typescript-eslint/eslint-plugin
npm ERR!   dev @typescript-eslint/eslint-plugin@"^6.0.0" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! 
npm ERR! For a full report see:
npm ERR! /Users/liz/.npm/_logs/2024-06-14T07_00_54_179Z-eresolve-report.txt

npm ERR! A complete log of this run can be found in: /Users/liz/.npm/_logs/2024-06-14T07_00_54_179Z-debug-0.log
godmmt commented 2 weeks ago

Error

liz at LMP in ~/Desktop/isuncoin (main●●) 
$ npx eslint . --ext .js,.jsx,.ts,.tsx

Oops! Something went wrong! :(

ESLint: 8.57.0

ESLint couldn't find the config "airbnb" to extend from. Please check that the name of the config is correct.

The config "airbnb" was referenced from the config file in "/Users/liz/Desktop/isuncoin/.eslintrc.js".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.

liz at LMP in ~/Desktop/isuncoin (main●●) 
$ npm i eslint-config-airbnb 
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! 
npm ERR! While resolving: @typescript-eslint/eslint-plugin@7.13.0
npm ERR! Found: @typescript-eslint/parser@6.21.0
npm ERR! node_modules/@typescript-eslint/parser
npm ERR!   dev @typescript-eslint/parser@"^6.21.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer @typescript-eslint/parser@"^7.0.0" from @typescript-eslint/eslint-plugin@7.13.0
npm ERR! node_modules/@typescript-eslint/eslint-plugin
npm ERR!   peer @typescript-eslint/eslint-plugin@"^7.0.0" from eslint-config-airbnb-typescript@18.0.0
npm ERR!   node_modules/eslint-config-airbnb-typescript
npm ERR!     eslint-config-airbnb-typescript@"^18.0.0" from the root project
npm ERR!   dev @typescript-eslint/eslint-plugin@"^7.13.0" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: @typescript-eslint/parser@7.13.0
npm ERR! node_modules/@typescript-eslint/parser
npm ERR!   peer @typescript-eslint/parser@"^7.0.0" from @typescript-eslint/eslint-plugin@7.13.0
npm ERR!   node_modules/@typescript-eslint/eslint-plugin
npm ERR!     peer @typescript-eslint/eslint-plugin@"^7.0.0" from eslint-config-airbnb-typescript@18.0.0
npm ERR!     node_modules/eslint-config-airbnb-typescript
npm ERR!       eslint-config-airbnb-typescript@"^18.0.0" from the root project
npm ERR!     dev @typescript-eslint/eslint-plugin@"^7.13.0" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! 
npm ERR! For a full report see:
npm ERR! /Users/liz/.npm/_logs/2024-06-14T07_05_06_933Z-eresolve-report.txt

npm ERR! A complete log of this run can be found in: /Users/liz/.npm/_logs/2024-06-14T07_05_06_933Z-debug-0.log
godmmt commented 2 weeks ago

原因是 @typescript-eslint/parser 和 @typescript-eslint/eslint-plugin 的不同版本之間的依賴衝突。

npm install @typescript-eslint/parser@latest @typescript-eslint/eslint-plugin@latest

應該可以解決。

godmmt commented 2 weeks ago

再次執行 npx eslint . --ext .js,.jsx,.ts,.tsx

New error:

liz at LMP in ~/Desktop/isuncoin (main●●) 
$ npx eslint . --ext .js,.jsx,.ts,.tsx

Oops! Something went wrong! :(

ESLint: 8.57.0

ESLint couldn't find the plugin "@babel/eslint-plugin".

(The package "@babel/eslint-plugin" was not found when loaded as a Node module from the directory "/Users/liz/Desktop/isuncoin".)

It's likely that the plugin isn't installed correctly. Try reinstalling by running the following:

    npm install @babel/eslint-plugin@latest --save-dev

The plugin "@babel/eslint-plugin" was referenced from the config file in ".eslintrc.js".

If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.
godmmt commented 2 weeks ago
npm install @babel/eslint-plugin@latest --save-dev
godmmt commented 2 weeks ago

Error:

liz at LMP in ~/Desktop/isuncoin (main●●) 
$ npx eslint . --ext .js,.jsx,.ts,.tsx

/Users/liz/Desktop/isuncoin/.eslintrc.js
  0:0  error  Parsing error: Cannot read file '/Users/liz/Desktop/isuncoin/tsconfig.eslint.json'

/Users/liz/Desktop/isuncoin/jest.config.js
  0:0  error  Parsing error: Cannot read file '/Users/liz/Desktop/isuncoin/tsconfig.eslint.json'

/Users/liz/Desktop/isuncoin/next-env.d.ts
  0:0  error  Parsing error: Cannot read file '/Users/liz/Desktop/isuncoin/tsconfig.eslint.json'

/Users/liz/Desktop/isuncoin/src/pages/_app.tsx
  0:0  error  Parsing error: Cannot read file '/Users/liz/Desktop/isuncoin/tsconfig.eslint.json'

/Users/liz/Desktop/isuncoin/src/pages/_document.tsx
  0:0  error  Parsing error: Cannot read file '/Users/liz/Desktop/isuncoin/tsconfig.eslint.json'

/Users/liz/Desktop/isuncoin/src/pages/api/hello.ts
  0:0  error  Parsing error: Cannot read file '/Users/liz/Desktop/isuncoin/tsconfig.eslint.json'

/Users/liz/Desktop/isuncoin/src/pages/index.tsx
  0:0  error  Parsing error: Cannot read file '/Users/liz/Desktop/isuncoin/tsconfig.eslint.json'

/Users/liz/Desktop/isuncoin/src/tests/sample.test.ts
  0:0  error  Parsing error: Cannot read file '/Users/liz/Desktop/isuncoin/tsconfig.eslint.json'

/Users/liz/Desktop/isuncoin/tailwind.config.ts
  0:0  error  Parsing error: Cannot read file '/Users/liz/Desktop/isuncoin/tsconfig.eslint.json'

✖ 9 problems (9 errors, 0 warnings)

新增 tsconfig.eslint.json:

{
  "extends": ["./tsconfig.json"],
  "include": ["**/*.ts", "**/*.tsx", "*.ts", "**/*.js", "**/*.jsx", "*.js", ".eslintrc.js"]
}
godmmt commented 2 weeks ago

Error:

liz at LMP in ~/Desktop/isuncoin (main●●) 
$ npx eslint . --ext .js,.jsx,.ts,.tsx

/Users/liz/Desktop/isuncoin/src/pages/index.tsx
   36:12  error  Arbitrary value detected in 'before:h-[300px]'                         tailwindcss/no-arbitrary-value
   36:12  error  Arbitrary value detected in 'sm:before:w-[480px]'                      tailwindcss/no-arbitrary-value
   36:12  error  Arbitrary value detected in 'before:content-['']'                      tailwindcss/no-arbitrary-value
   36:12  error  Arbitrary value detected in 'after:h-[180px]'                          tailwindcss/no-arbitrary-value
   36:12  error  Arbitrary value detected in 'sm:after:w-[240px]'                       tailwindcss/no-arbitrary-value
   36:12  error  Arbitrary value detected in 'after:content-['']'                       tailwindcss/no-arbitrary-value
   36:12  error  Arbitrary value detected in 'after:dark:via-[#0141ff]/40'              tailwindcss/no-arbitrary-value
   36:12  error  Arbitrary value detected in 'before:lg:h-[360px]'                      tailwindcss/no-arbitrary-value
   38:11  error  Arbitrary value detected in 'dark:drop-shadow-[0_0_0.3rem_#ffffff70]'  tailwindcss/no-arbitrary-value
   60:14  error  Arbitrary value detected in 'max-w-[30ch]'                             tailwindcss/no-arbitrary-value
   77:14  error  Arbitrary value detected in 'max-w-[30ch]'                             tailwindcss/no-arbitrary-value
   94:14  error  Arbitrary value detected in 'max-w-[30ch]'                             tailwindcss/no-arbitrary-value
  111:14  error  Arbitrary value detected in 'max-w-[30ch]'                             tailwindcss/no-arbitrary-value

✖ 13 problems (13 errors, 0 warnings)
godmmt commented 2 weeks ago
$ npx eslint . --ext .js,.jsx,.ts,.tsx              

/Users/liz/Desktop/isuncoin/src/pages/index.tsx
   36:12  error    Arbitrary value detected in 'before:h-[300px]'                                                                                                                                                                                      tailwindcss/no-arbitrary-value
   36:12  error    Arbitrary value detected in 'sm:before:w-[480px]'                                                                                                                                                                                   tailwindcss/no-arbitrary-value
   36:12  error    Arbitrary value detected in 'before:content-['']'                                                                                                                                                                                   tailwindcss/no-arbitrary-value
   36:12  error    Arbitrary value detected in 'after:h-[180px]'                                                                                                                                                                                       tailwindcss/no-arbitrary-value
   36:12  error    Arbitrary value detected in 'sm:after:w-[240px]'                                                                                                                                                                                    tailwindcss/no-arbitrary-value
   36:12  error    Arbitrary value detected in 'after:content-['']'                                                                                                                                                                                    tailwindcss/no-arbitrary-value
   36:12  error    Arbitrary value detected in 'after:dark:via-[#0141ff]/40'                                                                                                                                                                           tailwindcss/no-arbitrary-value
   36:12  error    Arbitrary value detected in 'before:lg:h-[360px]'                                                                                                                                                                                   tailwindcss/no-arbitrary-value
   36:12  warning  Classname 'before:bg-gradient-radial' is not a Tailwind CSS class!                                                                                                                                                                  tailwindcss/no-custom-classname
   36:12  warning  Classname 'after:bg-gradient-conic' is not a Tailwind CSS class!                                                                                                                                                                    tailwindcss/no-custom-classname
   36:12  warning  The arbitrary class 'before:h-[300px], sm:before:w-[480px], after:h-[180px], sm:after:w-[240px], before:lg:h-[360px]' could be replaced by 'before:h-300px, sm:before:w-480px, after:h-180px, sm:after:w-240px, before:lg:h-360px'  tailwindcss/no-unnecessary-arbitrary-value
   38:11  error    Arbitrary value detected in 'dark:drop-shadow-[0_0_0.3rem_#ffffff70]'                                                                                                                                                               tailwindcss/no-arbitrary-value
   60:14  error    Arbitrary value detected in 'max-w-[30ch]'                                                                                                                                                                                          tailwindcss/no-arbitrary-value
   77:14  error    Arbitrary value detected in 'max-w-[30ch]'                                                                                                                                                                                          tailwindcss/no-arbitrary-value
   94:14  error    Arbitrary value detected in 'max-w-[30ch]'                                                                                                                                                                                          tailwindcss/no-arbitrary-value
  111:14  error    Arbitrary value detected in 'max-w-[30ch]'                                                                                                                                                                                          tailwindcss/no-arbitrary-value

✖ 16 problems (13 errors, 3 warnings)
  0 errors and 1 warning potentially fixable with the `--fix` option.

解決:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

關閉終端機 關閉 vscode 再重新啟動

將 index 中不符合 Tailwind CSS 語法的 className 修掉就OK了

godmmt commented 2 weeks ago
liz at LMP in ~/Desktop/isuncoin (main●●) 
$ npm run dev

> isuncoin@0.1.0 dev
> next dev

  ▲ Next.js 14.2.4
  - Local:        http://localhost:3000

 ✓ Starting...
 ✓ Ready in 7.8s
 ○ Compiling / ...

warn - No utility classes were detected in your source files. If this is unexpected, double-check the `content` option in your Tailwind CSS configuration.
warn - https://tailwindcss.com/docs/content-configuration
 ✓ Compiled / in 11.4s (287 modules)
 GET / 200 in 11729ms
<w> [webpack.cache.PackFileCacheStrategy] Caching failed for pack: Error: ENOENT: no such file or directory, lstat '/Users/liz/Desktop/isuncoin/.next/server'
<w> [webpack.cache.PackFileCacheStrategy/webpack.FileSystemInfo] Resolving '../../../../.next/server/pages/index' in /Users/liz/Desktop/isuncoin/node_modules/next/dist/server for build dependencies doesn't lead to expected result '/Users/liz/Desktop/isuncoin/.next/server/pages/index.js', but to 'Error: Can't resolve '../../../../.next/server/pages/index' in '/Users/liz/Desktop/isuncoin/node_modules/next/dist/server'' instead. Resolving dependencies are ignored for this path.
<w>  at resolve commonjs file ../../../../.next/server/pages/index (expected /Users/liz/Desktop/isuncoin/.next/server/pages/index.js)
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/server/require.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/server/require.js
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/server/load-components.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/server/load-components.js
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/utils.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/utils.js
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/handle-externals.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/handle-externals.js
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
<w>  at resolve commonjs /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
<w> [webpack.cache.PackFileCacheStrategy/webpack.FileSystemInfo] Resolving '../../../../.next/server/pages/_app' in /Users/liz/Desktop/isuncoin/node_modules/next/dist/server for build dependencies doesn't lead to expected result '/Users/liz/Desktop/isuncoin/.next/server/pages/_app.js', but to 'Error: Can't resolve '../../../../.next/server/pages/_app' in '/Users/liz/Desktop/isuncoin/node_modules/next/dist/server'' instead. Resolving dependencies are ignored for this path.
<w>  at resolve commonjs file ../../../../.next/server/pages/_app (expected /Users/liz/Desktop/isuncoin/.next/server/pages/_app.js)
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/server/require.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/server/require.js
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/server/load-components.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/server/load-components.js
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/utils.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/utils.js
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/handle-externals.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/handle-externals.js
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
<w>  at resolve commonjs /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
<w> [webpack.cache.PackFileCacheStrategy/webpack.FileSystemInfo] Resolving '../../../../.next/server/pages/_document' in /Users/liz/Desktop/isuncoin/node_modules/next/dist/server for build dependencies doesn't lead to expected result '/Users/liz/Desktop/isuncoin/.next/server/pages/_document.js', but to 'Error: Can't resolve '../../../../.next/server/pages/_document' in '/Users/liz/Desktop/isuncoin/node_modules/next/dist/server'' instead. Resolving dependencies are ignored for this path.
<w>  at resolve commonjs file ../../../../.next/server/pages/_document (expected /Users/liz/Desktop/isuncoin/.next/server/pages/_document.js)
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/server/require.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/server/require.js
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/server/load-components.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/server/load-components.js
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/utils.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/utils.js
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/handle-externals.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/handle-externals.js
<w>  at file dependencies /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
<w>  at file /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
<w>  at resolve commonjs /Users/liz/Desktop/isuncoin/node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
godmmt commented 2 weeks ago

Build ok

liz at LMP in ~/Desktop/isuncoin (main●●) 
$ npm run build

> isuncoin@0.1.0 build
> next build

  ▲ Next.js 14.2.4

 ✓ Linting and checking validity of types    
   Creating an optimized production build ...

warn - No utility classes were detected in your source files. If this is unexpected, double-check the `content` option in your Tailwind CSS configuration.
warn - https://tailwindcss.com/docs/content-configuration
 ✓ Compiled successfully
 ✓ Collecting page data    
 ✓ Generating static pages (3/3)
 ✓ Collecting build traces    
 ✓ Finalizing page optimization    

Route (pages)                             Size     First Load JS
┌ ○ /                                     4.08 kB        82.3 kB
├   /_app                                 0 B            78.2 kB
├ ○ /404                                  180 B          78.4 kB
└ ƒ /api/hello                            0 B            78.2 kB
+ First Load JS shared by all             79.8 kB
  ├ chunks/framework-ecc4130bc7a58a64.js  45.2 kB
  ├ chunks/main-2d94ec6e4d65c635.js       32 kB
  └ other shared chunks (total)           2.59 kB

○  (Static)   prerendered as static content
ƒ  (Dynamic)  server-rendered on demand
godmmt commented 2 weeks ago

Run dev 有2個 warning 但不是 error 就先擱置

$ npm run dev

> isuncoin@0.1.0 dev
> next dev

  ▲ Next.js 14.2.4
  - Local:        http://localhost:3000

 ✓ Starting...
 ✓ Ready in 2.9s
 ○ Compiling / ...

warn - No utility classes were detected in your source files. If this is unexpected, double-check the `content` option in your Tailwind CSS configuration.
warn - https://tailwindcss.com/docs/content-configuration
 ✓ Compiled / in 4.5s (289 modules)
 GET /_next/static/webpack/f32bb1c260c8d89b.webpack.hot-update.json 404 in 4653ms
 ⚠ Fast Refresh had to perform a full reload. Read more: https://nextjs.org/docs/messages/fast-refresh-reload
 GET / 200 in 4708ms
 GET / 200 in 24ms
godmmt commented 2 weeks ago

新專案資料夾中終端機輸入指令

npx create-next-app . --ts

npm install --save-dev lint-staged

新增 .lintstagedrc

// .lintstagedrc
{
  "**/*.{js,jsx,ts,tsx,css}": [
    // 會直接 format
    "prettier --write",
    // eslint check
    "eslint ."
  ]
}
npm install -D husky@4
npm install -D husky

修改 package.json:

  ...
  "husky": {
    "hooks": {
      "pre-commit": "npm run test && lint-staged"
    }
  },
  ...
npm install -D jest
npm install -D jest ts-jest @types/jest
godmmt commented 2 weeks ago

以下使用引用(quote)符號的內容,用來表示為 KM 原文的段落:

接著,我們在專案 root 資料夾內建立一個 tests folder,然後在 folder 內建立對應的測試檔案 (前端放在前端 root 資料夾,後端放在後端 root 資料夾)

新增 tests folder → src/tests/sample.test.ts (內容參考 iSunFA)

describe("Arithmetic operations", () => {
  test("Check the result of 5 + 2", () => {
    expect(5 + 2).toBe(7);
  });
});

[此處以 ts 為例子] 在 run 測試以前,我們先在 root 資料夾裡面建立一個 jest.config.js 檔案,並且修改設置 (若沒有需要使用 ts 請參閱 jest config 官網)

新增 jest.config.js : ❎

/** @type {~~import('ts-jest/dist/types').InitialOptionsTsJest~~} */
module.exports = {
  coverageDirectory: "coverage",
  preset: "ts-jest",
  testEnvironment: "node",
  testRegex: "(/tests/.*|(\\.|/)(test|spec))\\.tsx?$",
};

注意:InitialOptionsTsJest 已棄用。

jest.config.js : ← 改用這個 ✅

/** @type {import('jest').Config} */
const config = {
  verbose: true,
  preset: "ts-jest",
  testEnvironment: "node",
  testRegex: "(/tests/.*|(\\.|/)(test|spec))\\.tsx?$",
};

module.exports = config;
godmmt commented 2 weeks ago

修改 package.json:

  "scripts": {
    ...
    "test": "jest"
  },

Coding style 自動檢查與更新 - 安裝使用 Prettier

為了自動檢查排版相關的 coding style 問題,我們可以使用 npm 安裝 prettier 套件,而此套件可以幫我們找出不符合 coding style 的 code

安裝套件 prettier:

npm install --dev-dependency prettier

接著,因為我們的 coding style 與 prettier 所預設的排版不同,我們可以在 root 建立 .prettierrc 來設定我們所要的 coding style 規則,我們目前是參考 airbnb 的規則,以下附上 airbnb 的 prettier 設定檔

如果未來有做大幅的 coding style 調整,我們想要自定義規則,我們可以使用  prettier playground,並勾選頁面左方的 options 來產出符合我們所要的 coding style 的 .prettierrc 檔案

root 建立 .prettierrc :

{
  "$schema": "http://json.schemastore.org/prettierrc",
  "arrowParens": "always",
  "bracketSpacing": true,
  "jsxSingleQuote": false,
  "printWidth": 100,
  "proseWrap": "always",
  "quoteProps": "as-needed",
  "semi": true,
  "singleQuote": true,
  "tabWidth": 2,
  "trailingComma": "es5",
  "useTabs": false,
  "plugins": ["prettier-plugin-tailwindcss"]
}
godmmt commented 2 weeks ago

修改 package.json :

"scripts": {
    ...
    "check-format": "prettier --ignore-path .gitignore --list-different \"**/*.+(js|ts|json)\"",
},
"scripts": {
    ...
    "format": "prettier --ignore-path .gitignore --write \"**/*.+(js|ts|json)\""
},
npm run format

執行後會告訴你有哪些檔案被檢查了、並且有沒有改變: %E6%88%AA%E5%9C%96_2024-06-14_%E4%B8%8A%E5%8D%8811 48 11

godmmt commented 2 weeks ago
npm install --dev-dependency eslint

npm install @typescript-eslint/eslint-plugin@latest --save-dev
npm install @typescript-eslint/parser --save-dev

接著,在 root 新增 .eslintrc.js 檔案:

module.exports = {
  parserOptions: {
    ecmaVersion: 2020, // 支援 ECMAScript2020
    sourceType: "module", // 使用 ECMAScript ****module
    ecmaFeatures: {
      jsx: true, // 支援 JSX
      experimentalObjectRestSpread: true,
    },
  },
  // 加上 ts 相關規則
  overrides: [
    {
      files: ["*.ts", "*.tsx"],
      extends: ["plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended", "plugin:import/recommended"],
      parser: "@typescript-eslint/parser",
      plugins: ["@typescript-eslint"],
    },
  ],
  extends: ["plugin:import/typescript"],
  // 加上 no console log 規則
  rules: {
    "no-console": "error",
  },
  // 整合 prettier 和解決 prettier 衝突問題
  plugins: ["prettier"],
};

如果有被安裝 .eslintrc.json ,就刪除它。

執行

npm install eslint-plugin-import@latest --save-dev
npm install eslint-plugin-prettier@latest --save-dev

在 package.json 的 script 中新增 lint

  "scripts": {
        ...
    "lint": "eslint --ignore-path .gitignore ."
  }

最後,為了方便可以一次使用 check-format 、 eslint ,我們可以在 package.json 中將其整合成一個 validate 指令

  "scripts": {
        ...
    "validate": "npm run test && npm run check-format && npm run lint"
  }

總之,package.json 目前長這樣:

  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "eslint --ignore-path .gitignore .",
    "test": "jest",
    "check-format": "prettier --ignore-path .gitignore --list-different \"**/*.+(js|ts|json)\"",
    "format": "prettier --ignore-path .gitignore --write \"**/*.+(js|ts|json)\"",
    "validate": "npm run test && npm run check-format && npm run lint"
  },

對比 iSinFA : ← ✅ (我改抄這個)

  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint && eslint --fix --ext .js,.jsx,.ts,.tsx .",
    "test": "jest",
    "check-format": "prettier --ignore-path .gitignore --list-different \"**/*.+(js|jsx|ts|tsx|json)\"",
    "format": "prettier --ignore-path .gitignore --write \"**/*.+(js|jsx|ts|tsx|json)\"",
    "validate": "npm run test && npm run check-format && npm run lint"
  },
godmmt commented 2 weeks ago

Tailwind css setting

npm install -D eslint-plugin-tailwindcss prettier-plugin-tailwindcss

.eslintrc.js 加上:

...
extends: [..., 'plugin:tailwindcss/recommended'],
...
rules: {
  ...
  'tailwindcss/no-contradicting-classname': 'error',
  'tailwindcss/classnames-order': 'off',
  'tailwindcss/enforces-negative-arbitrary-values': 'error',
  'tailwindcss/enforces-shorthand': 'off',
  'tailwindcss/migration-from-tailwind-2': 'error',
  'tailwindcss/no-arbitrary-value': 'error',
  'tailwindcss/no-custom-classname': 'error',
},
...
settings: {
  tailwindcss: {
    // These are the default values but feel free to customize
    callees: ['classnames', 'clsx', 'ctl'],
    config: 'tailwind.config.js',
    cssFiles: ['**/*.css', '!**/node_modules', '!**/.*', '!**/dist', '!**/build'],
    cssFilesRefreshRate: '5_000',
    removeDuplicates: true,
    whitelist: [],
  },
},
...

把  .lintstagedrc  改成  .lintstagedrc.json  並更改內容,讓 lint-staged 依照副檔名分開檢查 :

(第一種)

{
  "/*.+(js|jsx|ts|tsx)": ["./node_modules/.bin/eslint --fix", "./node_modules/.bin/prettier --write", "git add"],
  "/*.+(css)": ["./node_modules/.bin/eslint/tailwindcss --fix", "./node_modules/.bin/prettier --write", "git add"]
}

參考 iSunFA:(第二種) ← 選這個 ✅

{
  "**/*.+(js|jsx|ts|tsx)": ["./node_modules/.bin/eslint --fix", "./node_modules/.bin/prettier --write", "git add"],
  "**/*.+(css)": ["./node_modules/.bin/eslint/tailwindcss --fix", "./node_modules/.bin/prettier --write", "git add"]
}

兩者差異在於

第一種:

第二種:

何時使用哪個配置?

一:適合於僅需要處理根目錄中的相應文件,而不包括子目錄中的文件。

二:適合於需要處理整個項目中所有相應文件的情況,無論它們位於哪個目錄。

假設資料夾結構如下:

project/
├── src/
│   ├── index.js
│   ├── App.tsx
│   └── styles.css
└── index.js
godmmt commented 2 weeks ago
npm install eslint-config-airbnb-typescript \
            @typescript-eslint/eslint-plugin@^6.0.0 \
            @typescript-eslint/parser@^6.0.0 \
            --save-dev

執行  npx eslint . --ext .js,.jsx,.ts,.tsx

會遇到這種衝突:

liz at LMP in ~/Desktop/isuncoin (main●●)
$ npx eslint . --ext .js,.jsx,.ts,.tsx

Oops! Something went wrong! :(

ESLint: 8.57.0

ESLint couldn't find the config "airbnb" to extend from. Please check that the name of the config is correct.

The config "airbnb" was referenced from the config file in "/Users/liz/Desktop/isuncoin/.eslintrc.js".

If you still have problems, please stop by https://eslint.org/chat/help to chat with the team.
npm install @typescript-eslint/parser@latest @typescript-eslint/eslint-plugin@latest
module.exports = {
  parser: "@typescript-eslint/parser",
  parserOptions: {
    parser: "@babel/eslint-parser",
    ecmaVersion: 2020,
    sourceType: "module",
    ecmaFeatures: {
      jsx: true,
      experimentalObjectRestSpread: true,
    },
    project: "./tsconfig.eslint.json",
  },
  // 加上 ts 相關規則
  overrides: [
    {
      files: ["*.ts", "*.tsx", "**/*.ts", "**/*.tsx"],
      extends: [
        "airbnb",
        "airbnb-typescript",
        "plugin:@typescript-eslint/eslint-recommended",
        "plugin:@typescript-eslint/recommended",
        "plugin:import/recommended",
      ],
      parser: "@typescript-eslint/parser",
      plugins: ["@typescript-eslint"],
      rules: {
        "object-curly-newline": "off",
        "react/jsx-props-no-spreading": "off",
        "no-console": "error",
        "tailwindcss/no-contradicting-classname": "error",
        "tailwindcss/classnames-order": "off",
        "tailwindcss/enforces-negative-arbitrary-values": "error",
        "tailwindcss/enforces-shorthand": "off",
        "tailwindcss/migration-from-tailwind-2": "error",
        "tailwindcss/no-arbitrary-value": "error",
        "tailwindcss/no-custom-classname": "warn",
      },
    },
  ],
  extends: [
    "airbnb",
    "airbnb-typescript",
    "plugin:import/typescript",
    "plugin:tailwindcss/recommended",
    "plugin:@next/next/recommended",
    "plugin:react/recommended",
  ],
  rules: {
    "no-console": "error",
    "tailwindcss/no-contradicting-classname": "error",
    "tailwindcss/classnames-order": "off",
    "tailwindcss/enforces-negative-arbitrary-values": "error",
    "tailwindcss/enforces-shorthand": "off",
    "tailwindcss/migration-from-tailwind-2": "error",
    "tailwindcss/no-arbitrary-value": "error",
    "tailwindcss/no-custom-classname": "warn",
    "object-curly-newline": "off",
    "react/jsx-props-no-spreading": "off",
  },

  // 整合 prettier 和解決 prettier 衝突問題
  plugins: ["tailwindcss", "@babel", "prettier", "react"],
  settings: {
    tailwindcss: {
      // These are the default values but feel free to customize
      callees: ["classnames", "clsx", "ctl"],
      config: "tailwind.config.ts",
      cssFiles: ["**/*.css", "!**/node_modules", "!**/.*", "!**/dist", "!**/build"],
      cssFilesRefreshRate: "5_000",
      removeDuplicates: true,
      whitelist: [],
    },
    react: {
      version: "detect",
    },
  },
  // 讓 eslint 知道我們在使用 jest ,這樣在跑 test.js 時 eslint 就不會報 jest 關鍵字的錯誤了
  env: { browser: true, node: true, es6: true, jest: true },
};

執行:

npm install @babel/eslint-plugin@latest --save-dev
godmmt commented 2 weeks ago

參考:https://tailwindcss.com/docs/guides/nextjs

重新安裝:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

修改 postcss.config.js:

module.exports = {
  plugins: {
    tailwindcss: {
      config: "./tailwind.config.ts",
    },
    autoprefixer: {},
  },
};
godmmt commented 2 weeks ago

took 6.5 hours

done