Nextjs with eslint, prettier

Nextjs with eslint, prettier

Date
Oct 27, 2022
Property
Medium
Created by
Status
Done
Tags
nextjs
eslint
prettier

Create nextjs project

yarn create next-app --typescript
 
and go to root path in project:
cd <your project name>
 

Config Setting for eslint

yarn eslint .
 
and modify your .eslint.json file:
{ "extends": "next/core-web-vitals", "rules": { "prefer-const": "error" } }
 
If you run this project with vs code, you should add this settings for .vscode/settings.json
{ "editor.codeActionsOnSave": { "source.fixAll.eslint": true } }
 

Install devDependency and set config

yarn add --dev @typescript-eslint/eslint-plugin
 
check your .eslintrc.json with this setting:
{ "plugins": ["@typescript-eslint"], "extends": [ "next/core-web-vitals", "plugin:@typescript-eslint/recommended" ], "rules": { "@typescript-eslint/no-unused-vars": "error", "@typescript-eslint/no-explicit-any": "error" } }
 

Configure your Prettier

Install prettier devDependency
yarn add --dev prettier eslint-config-prettier
 
Create a .prettierrc.json file , and configure it with following content.
{ "semi": false, "trailingComma": "es5", "singleQuote": true, "tabWidth": 2, "useTabs": false }
 
add this setting to your .eslintrc.json
{ //... "extends": [ "next/core-web-vitals", "plugin:@typescript-eslint/recommended", "prettier" ], //... }
 

VSCode setting

  1. install VSCode's prettier plugin
  1. editing .vscode/settings.json like this:
{ "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "editor.formatOnSave": true, // Tell VSCode to format files on save "editor.defaultFormatter": "esbenp.prettier-vscode" // Tell VSCode to use Prettier as default file formatter }

Husky

Pre-check error, linting and formatting on commit
 
install husky
yarn add --dev husky
 
enable husky
yarn husky install
 
add the git hook
yarn husky add .husky/pre-commit "yarn tsc --noEmit && yarn eslint . && yarn prettier --write ."
 

Lint staged

help you to check project code with lint when running a git commit. (Before it's too late XD)
 
Install lint-staged
yarn add --dev lint-staged
 
Create a configuration lint-staged.config.js file, and configure it.
// lint-staged.config.js module.exports = { // Type check TypeScript files '**/*.(ts|tsx)': () => 'yarn tsc --noEmit', // Lint then format TypeScript and JavaScript files '**/*.(ts|tsx|js)': (filenames) => [ `yarn eslint --fix ${filenames.join(' ')}`, `yarn prettier --write ${filenames.join(' ')}`, ], // Format MarkDown and JSON '**/*.(md|json)': (filenames) => `yarn prettier --write ${filenames.join(' ')}`, }
 

Pre-commit hook

change the .husky/pre-commit file, and configure it like following content.
#!/bin/sh . "$(dirname "$0")/_/husky.sh" yarn lint-staged
 

Done

Try to use git commit, and check the project will auto pre-check and analysis after runnung git commit order.