[Series] Setup Source Template for Vue 3 – Phần 3

Giới thiệu Chào tất cả các bạn, phần 2 mình đã hướng dẫn các bạn setup về vue-router, pinia, vitest. Trong phần này mình tiếp tục hướng dẫn các bạn setup về Eslint, Prettier và Commitlint Nội Dung ⚡️ Vue 3, Vite, pnpm 📦 Components auto importing 🎨 UnoCSS – 1 thư viện lấy ý

Giới thiệu

Chào tất cả các bạn, phần 2 mình đã hướng dẫn các bạn setup về vue-router, pinia, vitest. Trong phần này mình tiếp tục hướng dẫn các bạn setup về Eslint, PrettierCommitlint

Nội Dung

Đây là cấu trúc thư mục của dự án sau khi setup.

vue-template/
 ├── public/
 |    ├── favicon.ico
 ├── src/
 |    ├── assets/
 |    |    └── logo.png
 |    ├── components/
 |    |    └── HelloWorld.vue
 |    ├── core/
 |    ├── hooks/
 |    |    └── useAuth.ts
 |    ├── layouts/
 |    |    └── BlankLayout.vue
 |    |    └── MainLayout.vue
 |    ├── pages/
 |    |    └── Dashboard.vue
 |    |    └── Error.vue
 |    |    └── NotFound.vue
 |    ├── routes/
 |    |    └── index.ts
 |    ├── stores/
 |    |    └── auth.ts
 |    ├── test/
 |    |    └── components/
 |    |    |    └── Sample.spec.ts
 |    ├── App.vue
 |    └── main.ts
 |    └── vite-env.d.ts
 |    └── vue-shim.d.ts
 ├── package.json
 ├── README.md
 ├── .cz-config.ts
 ├── .env.sample
 ├── .eslintrc
 ├── .prettierrc
 ├── .commitlint.config.cjs
 ├── tsconfig.json
 ├── tsconfig.node.json
 └── vite.config.js
 └── unocss.config.ts

Cài đặt

Trong phần này mình sẽ hướng dẫn các bạn setup về: 🔥 Eslint, prettier, commitlint

Eslint

ESLint là một open source giúp bạn tìm và khắc phục sự cố với mã JavaScript của mình. Không quan trọng bạn đang viết JavaScript trong trình duyệt hay trên máy chủ, ESLint có thể giúp code của bạn hoạt động tốt nhất.

pnpm i -D eslint

eslint-config-prettier

Plugin này Tắt tất cả các quy tắc không cần thiết hoặc có thể xung đột với Prettier. Nó cho phép bạn sử dụng cấu hình của mình mà không để các cấu hình của nó cản trở khi sử dụng Prettier.

Lưu ý rằng config này chỉ tắt các quy tắc, vì vậy chỉ nên sử dụng config này cùng với một số config khác.

pnpm i -D eslint-config-prettier

Sau đó, thêm “prettier” vào mảng “extends” trong file .eslintrc của bạn. Đảm bảo đặt nó ở vị trí cuối cùng để nó có thể ghi đè lên các cấu hình khác.

{"root":true,"env":{"browser":true},"extends":["prettier"],}

eslint-plugin-prettier

Chạy Prettier dưới dạng quy tắc ESLint và báo cáo sự khác biệt dưới dạng các sự cố ESLint.

Nếu định dạng mong muốn của bạn không khớp với đầu ra của Prettier, bạn nên sử dụng một công cụ khác chẳng hạn như prettier-eslint để thay thế.

pnpm i -D eslint-config-prettier

Sau đó, bạn cần thêm plugin:prettier/recommended vào mảng “extends” trong file .eslintrc của bạn.

{"extends":["plugin:prettier/recommended"]}

eslint-plugin-vue

Plugin ESLint chính thức cho Vue.js. Nó cho phép chúng ta kiểm tra <template> và <script> của các file .vue bằng ESLint, cũng như code Vue trong các file .js.

Lưu ý: Bắt buộc ESLint v6.2.0 trở lên và Node.js v14.17.x, v16.x trở lên.

pnpm i -D eslint-plugin-vue

Sau đó, bạn cần thêm plugin:vue/vue3-recommended vào mảng “extends” trong file .eslintrc của bạn.

{"extends":["plugin:vue/vue3-recommended"]}

Cài đặt 1 số plugin ESLint cung cấp các quy tắc lint cho cơ sở mã TypeScript.

pnpm i -D @typescript-eslint/eslint-plugin @typescript-eslint/parser @vue/eslint-config-typescript @vue/test-utils

Đây là file eslint đầy đủ sau khi các bạn cài đặt xong các plugin trên:

// .eslintrc{"root":true,"env":{"browser":true},"extends":["eslint:recommended","plugin:vue/vue3-recommended","@vue/eslint-config-typescript","prettier"],"rules":{},"ignorePatterns":["node_modules/*","dist/*","public/*"]//  các thư mục trong mảng này nó sẽ bỏ qua và không check lỗi}

Bạn có thể thêm script để kiểm tra tất cả các file trong project của mình:

"scripts":{"lint":"eslint --ext .js,.ts,.vue --ignore-path .gitignore src",// check lỗi eslint"lint:fix":"eslint --ext .js,.ts,.vue --ignore-path .gitignore --fix src",// check và fix lỗi eslint có thể fix nhưng không phải là hoàn toàn }

Prettier

Prettier nó giúp chúng ta code theo chuẩn mà mình mong muốn ( bản chất nó là rule do mình quy định nên mỗi người sẽ có rule khác nhau :v ).

pnpm i -D prettier

Sau đó, bạn cần tạo 1 file .prettierrc

{"semi":false,// Không sử dụng dấu chấm phẩy để kết thúc câu lệnh."singleQuote":true,// Sử dụng dấu ngoặc đơn (' ') để gọi chuỗi."arrowParens":"avoid",// Tránh sử dụng dấu ngoặc cho hàm Arrow Function nếu nó chỉ có một tham số."tabWidth":2,// Chiều rộng của một tab là 2 khoảng trắng."printWidth":120// Chiều rộng cho phép của một dòng mã nguồn là 120 ký tự.}

Bạn có thể thêm 1 đoạn script để chạy format cho tất cả các file trong project của mình:

"scripts":{
    ...
    "format":"prettier .  --write",
    ...
 },

Commitlint

Commitlint giúp nhóm của bạn tuân thủ quy ước commit chung của team, để người review có thể review 1 cách trực quan hơn,…

pnpm i -D commitlint

Sau đó, các bạn cài thư viện commitizen để chạy commit trong terminal

pnpm i -g commitizen

Tiếp theo, các bạn cài thêm emoji và plugin cho commitlint

pnpm i -D commitlint-config-gitmoji cz-customizable

Tiếp theo, các bạn tạo 1 file commitlint.config.cjs và thêm config.

// eslint-disable-next-line no-undef
module.exports = {
  extends:['gitmoji'],
  rules:{
    'header-max-length':[0, 'always',100],},}

Tiếp theo, các bạn tạo 1 file .cz-config.ts để config rule commit của các bạn.

module.exports ={
 types:[{ value:':sparkles: feat', name:'✨ feat:tAdding a new feature'},{ value:':bug: fix', name:'🐛 fix:tFixing a bug'},{ value:':construction: wip', name:'🚧 wip:tWork in progress'},{
     value:':lipstick: style',
     name:'💄 style:tAdd or update styles, ui or ux',},{
     value:':hammer: refactor',
     name:'🔨 refactor:tCode change that neither fixes a bug nor adds a feature',},{ value:':memo: docs', name:'📝 docs:tAdd or update documentation'},{
     value:':zap: perf',
     name:'⚡️ perf:tCode change that improves performance',},{
     value:':white_check_mark: test',
     name:'✅ test:tAdding tests cases',},{ value:':rewind: revert', name:'⏪️ revert:tRevert to a commit'},{
     value:':construction_worker: build',
     name:'👷 build:tAdd or update regards to build process',},{
     value:':racehorse: ci',
     name:'🐎 ci:tAdd or update regards to CI process',},],

 scopes:[{ name:'all platforms'},{ name:'desktop'},{ name:'mobile'},{ name:'packages'},{ name:'unit test'},{ name:'settings'},{ name:'code convention'},],

 messages:{
   type:"***************** 🎼🎧🎉 Select the type of change that you're committing *****************:",
   scope:'n😪 Denote the SCOPE of this change (optional):',// used if allowCustomScopes is true
   customScope:'🎁 Denote the SCOPE of this change:',
   subject:'🔖 Subject - Write a SHORT, IMPERATIVE tense description of the change:n',
   body:'📝 Body - Provide a LONGER description of the change (optional). Use "|" to break new line:n',
   breaking:'💥 List any BREAKING CHANGES (optional):n',
   footer:'🔚 List any ISSUES CLOSED by this change (optional). E.g.: #31, #34:n',
   confirmCommit:'😄 Are you sure you want to proceed with the commit above?',},

 scopeOverrides:{
   fix:[{ name:'merge'},{ name:'style'},{ name:'test'},{ name:'hotfix'}],},

 allowCustomScopes:true,
 allowBreakingChanges:['feat','fix'],// skip any questions you want
 skipQuestions:[],
 subjectLimit:100,}

Tiếp theo, các bạn thêm config vào file package.json

"scripts":{
    ...
    "cm":"cz"
    ...
 },"lint-staged":{"src/**/*.{js,jsx,ts,tsx}":["pnpm run lint","pnpm run format"],"**/*.{js,jsx,ts,tsx,css,scss,md,json}":["pnpm run format"]},"config":{"commitizen":{"path":"./node_modules/cz-customizable"},"cz-customizable":{"config":".cz-config.ts"}}

Tiếp theo, bạn cài đặt husky ( Husky được sử dụng để tạo các thông báo commit, run tests, lint code, v.v… khi bạn commit hoặc push code ).

pnpm i -D husky lint-staged

Tiếp theo, các bạn chạy lệnh:

pnpm dlx husky-init &&pnpminstall

Tiếp theo, các bạn thêm file config vào trong folder .husky:

// commit-msg
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

npx commitlint --edit $1
// pre-commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"

pnpm lint-staged
// pre-push
#!/usr/bin/env sh
. "$(dirname "$0")/_/husky.sh"

pnpm run test

Và cuối cùng chúng ta có thể chạy test thử xem nó đã hoạt động hay chưa nhé :v

pnpm run cm

Chọn loại commit (theo hình ở dưới thì mình chọn **
**):

All lines except first will be wrapped after 100 characters.
? ***************** 🎼🎧🎉 Select the type of change that you're committing *****************: 
  👷 build:     Add or update regards to build process 
  🐎 ci:        Add or update regards to CI process 
  ✨ feat:      Adding a new feature 
❯ 🐛 fix:       Fixing a bug 
  🚧 wip:       Work in progress 
  💄 style:     Add or update styles, ui or ux 
  🔨 refactor:  Code change that neither fixes a bug nor adds a feature 

Chọn scope của loại commit:

😪 Denote the SCOPE of this change (optional): (Use arrow keys)
❯ all platforms 
 desktop 
 mobile 
 packages 
 unit test 
 settings 
 code convention 

Viết mô tả ngắn cho commit:

? 🔖 Subject - Write a SHORT, IMPERATIVE tense description of the change:
 setup eslint & prettier & commitlint

Viết mô tả dài cho commit:

? 📝 Body - Provide a LONGER description of the change (optional). Use "|" to break new line:// này thì tuỳ chọn nếu bạn nào muốn viết chi tiết thì ghi ở đây

Viết số issue trong task của mình:

? 🔚 List any ISSUES CLOSED by this change (optional). E.g.: #31, #34:
  #Issue-1

Sau đó, nó sẽ hiển thị như thế này:


###--------------------------------------------------------###
:bug: fix(all platforms): setup eslint & prettier & commitlint
###--------------------------------------------------------###

? 😄 Are you sure you want to proceed with the commit above? (Yneh) 

Mình Enter và chờ các script chạy eslint và prettier :v

Sau khi hoàn thành commit thì nó sẽ hiển thị như thế này:


###--------------------------------------------------------###
→ No staged files match any configured task.
[feat/chapter-2 44e3f9b]:bug: fix(all platforms): setup eslint & prettier & commitlint
 1 file changed,1 deletion(-)

Như vậy là các bạn đã setup thành công.

Kết bài

Vậy là mình đã hoàn thành setup xong eslint, prettier, commitlint. Cám ơn các bạn đã theo dõi series của mình. Hẹn các bạn ở bài viết tiếp theo. Nếu các bạn trong quá trình setup mà có vướng mắc gì thì các bạn cứ comment dưới đây mình sẽ cố gắng support các bạn và giải đáp các thắc mắc của bạn. Tks all

Nguồn: viblo.asia

Bài viết liên quan

Thay đổi Package Name của Android Studio dể dàng với plugin APR

Nếu bạn đang gặp khó khăn hoặc bế tắc trong việc thay đổi package name trong And

Lỗi không Update Meta_Value Khi thay thế hình ảnh cũ bằng hình ảnh mới trong WordPress

Mã dưới đây hoạt động tốt có 1 lỗi không update được postmeta ” meta_key=

Bài 1 – React Native DevOps các khái niệm và các cài đặt căn bản

Hướng dẫn setup jenkins agent để bắt đầu build mobile bằng jenkins cho devloper an t

Chuyển đổi từ monolith sang microservices qua ví dụ

1. Why microservices? Microservices là kiến trúc hệ thống phần mềm hướng dịch vụ,