🖍️
Developer Note
  • Welcome
  • Git
    • Eslint & Prettier & Stylelint & Husky
  • Programming Language
    • JavaScript
      • Script Async vs Defer
      • Module
      • Const VS Let VS Var
      • Promise
      • Event Loop
      • Execution Context
      • Hoisting
      • Closure
      • Event Buddling and Capturing
      • Garbage Collection
      • This
      • Routing
      • Debounce and Throttle
      • Web Component
      • Iterator
      • Syntax
      • String
      • Array
      • Object
      • Proxy & Reflect
      • ProtoType
      • Class
      • Immutability
      • Typeof & Instanceof
      • Npm (Node package manager)
    • TypeScript
      • Utility Type
      • Type vs Interface
      • Any vs Unknown vs Never
      • Void and undefined
      • Strict Mode
      • Namespace
      • Enum
      • Module
      • Generic
    • Python
      • Local Development
      • Uv
      • Asyncio & Event loop
      • Context Manager
      • Iterator & Generator
      • Fast API
      • Pydantic & Data Class
    • Java
      • Compilation and Execution
      • Data Type
      • Enumeration
      • Data Structure
      • Try Catch
      • InputStream and OutputStream
      • Concurrent
      • Unicode Block
      • Build Tools
      • Servlet
      • Java 8
  • Coding Pattern
    • MVC vs MVVM
    • OOP vs Functional
    • Error Handling
    • MVC vs Flux
    • Imperative vs Declarative
    • Design Pattern
  • Web Communication
    • REST API
      • Web Hook
      • CORS issue
    • HTTPS
    • GraphQL
      • REST API vs GraphQL
      • Implementation (NodeJS + React)
    • Server-Sent Event
    • Web Socket
    • IP
    • Domain Name System (DNS)
  • Frontend
    • Progressive Web App (PWA)
    • Single Page & Multiple Page Application
    • Search Engine Optimiaztion (SEO)
    • Web bundling & Micro-frontend
      • Webpack
        • Using Webpack to build React Application
        • Using Webpack to build react library
      • Vite
      • Using rollup to build react library
      • Implementing micro frontend
    • Web Security
      • CSRF & Nonce
      • XSS
      • Click hijacking
    • Cypress
    • CSS
      • Core
        • Box Model
        • Inline vs Block
        • Flexbox & Grid
        • Pseudo Class
        • Position
      • Tailwind CSS
        • Shadcn
      • CSS In JS
        • Material UI
    • React
      • Core
        • Component Pattern
        • React Lazy & Suspense
        • React Portal
        • Error Boundary
        • Rendering Methods
        • Environment Variable
        • Conditional CSS
        • Memo
        • Forward Reference
        • High Order Component (HOC) & Custom Hook
        • TypeScript
      • State Management
        • Redux
        • Recoil
        • Zustand
      • Routing
        • React Router Dom
      • Data Fetching
        • Axios & Hook
        • React Query
        • Orval
      • Table
        • React Table
      • Form & Validation
        • React Hook Form
        • Zod
      • NextJS
        • Page Router
        • App Router
      • React Native
    • Angular
    • Svelte
      • Svelte Kit
  • Backend
    • Cache
      • Browser Cache
      • Web Browser Storage
      • Proxy
      • Redis
    • Rate limit
    • Monitoring
      • Logging
      • Distributed Tracing
    • Load Test
    • Encryption
    • Authentication
      • Password Protection
      • Cookie & Session
      • JSON Web Token
      • SSO
        • OAuth 2.0
        • OpenID Connect (OIDC)
        • SAML
    • Payment
      • Pre-built
      • Custom
    • File Handling
      • Upload & Download (Front-end)
      • Stream & Buffer
    • Microservice
      • API Gateway
      • Service Discovery
      • Load Balancer
      • Circuit Breaker
      • Message Broker
      • BulkHead & Zipkin
    • Elastic Search
    • Database
      • SQL
        • Group By vs Distinct
        • Index
        • N + 1 problem
        • Normalization
        • Foreign Key
        • Relationship
        • Union & Join
        • User Defined Type
      • NOSQL (MongoDB)
      • Transaction
      • Sharding
      • Lock (Concurrency Control)
    • NodeJS
      • NodeJS vs Java Spring
      • ExpressJS
      • NestJS
        • Swagger
        • Class Validator & Validation Pipe
        • Passport (Authentication)
      • Path Module
      • Database Connection
        • Integrating with MYSQL
        • Sequalize
        • Integrating with MongoDB
        • Prisma
        • MikroORM
        • Mongoose
      • Streaming
      • Worker Thread
      • Passport JS
      • JSON Web Token
      • Socket IO
      • Bull MQ
      • Pino (Logging)
      • Yeoman
    • Spring
      • Spring MVC
      • Spring REST
      • Spring Actuator
      • Aspect Oriented Programming (AOP)
      • Controller Advice
      • Filter
      • Interceptor
      • Concurrent
      • Spring Security
      • Spring Boot
      • Spring Cloud
        • Resilience 4j
      • Quartz vs Spring Batch
      • JPA and Hibernate
      • HATEOS
      • Swagger
      • Unit Test (Java Spring)
      • Unit Test (Spring boot)
  • DevOp
    • Docker
    • Kubernetes
      • Helm
    • Nginx
    • File System
    • Cloud
      • AWS
        • EC2 (Virtual Machine)
        • Network
        • IAM
          • Role-Service Binding
        • Database
        • Route 53
        • S3
        • Message Queue
        • Application Service
        • Serverless Framework
        • Data Analysis
        • Machine Learning
        • Monitoring
        • Security
      • Azure
        • Identity
        • Compute Resource
        • Networking
        • Storage
        • Monitoring
      • Google Cloud
        • IAM
          • Workload Identity Federation
        • Compute Engine
        • VPC Network
        • Storage
        • Kubernetes Engine
        • App Engine
        • Cloud function
        • Cloud Run
        • Infra as Code
        • Pub/Sub
    • Deployment Strategy
    • Jenkins
    • Examples
      • Deploy NextJS on GCP
      • Deploy Spring on Azure
      • Deploy React on Azure
  • Domain Knowledge
    • Web 3
      • Blockchain
      • Cryptocurrency
    • AI
      • Prompt
      • Chain & Agent
      • LangChain
      • Chunking
      • Search
      • Side Products
Powered by GitBook
On this page
  • Introduction
  • Eslint
  • Prettier
  • Stylelint
  • Husky && Lint-Staged
  • VS Code
  • Reference

Was this helpful?

  1. Git

Eslint & Prettier & Stylelint & Husky

PreviousGitNextProgramming Language

Last updated 8 months ago

Was this helpful?

Introduction

  • To create the style standard so as to let the code becomes more beautiful

  • The dependency is installed when new react project is created

Eslint

  • Install the corresponding dependencies

npm install eslint-webpack-plugin eslint-config-prettier 
eslint-plugin-prettier eslint-plugin-react 
eslint-plugin-unused-imports babel-eslint @typescript-eslint/eslint-plugin
@typescript-eslint/parser
  • Install eslint plugin in vsCode for the hints

  • Create eslint config file - .eslintrc.js

  • React Version

// .eslintrc.js
module.exports = {
  parser: "babel-eslint",
  parserOptions: {
    ecmaVersion: 2020,
    ecmaFeatures: { jsx: true },
    sourceType: "module",
  },
  plugins: ["prettier", "unused-imports"],// use plugin
  extends: [
    "react-app",
    "plugin:react/recommended", // as prettier has different set of rule,
    "plugin:prettier/recommended",// we use the recommended set
  ],
  rules: {
    "react/react-in-jsx-scope": "error",  // must include import from react, otherwise show error
    "prettier/prettier": "warn", // styling warning based on prettier
    "react/prop-types": "off", 
    "prefer-const": "warn", // const type is preferred
    "jsx-a11y/anchor-is-valid": "warn",       
    "unused-imports/no-unused-imports": "warn", 
    "unused-imports/no-unused-vars": "warn",
  },
  ignorePatterns: ["generated*"],
};
  • NextJS + TypeScript Version

// .eslintrc.js
module.exports = {
  parser: "@typescript-eslint/parser",
  parserOptions: {
    ecmaVersion: 2020,
    ecmaFeatures: { jsx: true },
    sourceType: "module",
    tsconfigRootDir: __dirname,
    project: "./tsconfig.json",
  },
  plugins: ["prettier", "unused-imports"], // use plugin
  extends: [
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended", // as prettier has different set of rule,
    "plugin:prettier/recommended", // we use the recommended set
     "next", 
    "next/core-web-vitals"
  ],
  rules: {
    "prettier/prettier": "warn", // styling warning based on prettier
    "prefer-const": "warn", // const type is preferred
    "jsx-a11y/anchor-is-valid": "off",
    "unused-imports/no-unused-imports": "warn",
    "unused-imports/no-unused-vars": "warn",
  },
  ignorePatterns: ["generated*"],
};

Prettier

  • Install the dependency

npm install prettier
  • Create prettierrc file

// .prettierrc
{
    "semi": true,
    "printWidth": 80,
    "arrowParens": "always",
    "singleQuote": false,
    "tabWidth": 2,
    "useTabs": false
  }

Stylelint

  • Install the dependency

npm install stylelint stylelint-config-sass-guidelines
yarn add 
  • Install the plug-in in vsCode for hints

  • Create stylelint file

// .stylelintrc.js
module.exports = {
    "extends": [
        "stylelint-config-standard",
        "stylelint-config-prettier",
        "stylelint-config-sass-guidelines"
    ],
    "plugins": [
        "stylelint-scss",
        "stylelint-order"
    ],
    "rules": {
        "value-keyword-case": null,
        "selector-class-pattern": null,
        "comment-whitespace-inside" : "never",
        "at-rule-semicolon-space-before": null,
        "no-invalid-position-at-import-rule":null,
        "order/properties-alphabetical-order": null, 
        // beautify the bracket
        "block-opening-brace-newline-after":"always-multi-line",
        "block-closing-brace-newline-before": "always-multi-line",
        "declaration-empty-line-before": "never",
        "indentation": "tab",
        "max-empty-lines": 1,
        "function-name-case": null,
        // arrange the css order
        "order/properties-order": [ 
          "position",
          "top",
          "right",
          "bottom",
          "left",
          "z-index",
          "display",
          "justify-content",
          "align-items",
          "float",
          "clear",
          "overflow",
          "overflow-x",
          "overflow-y",
          "padding",
          "padding-top",
          "padding-right",
          "padding-bottom",
          "padding-left",
          "margin",
          "margin-top",
          "margin-right",
          "margin-bottom",
          "margin-left",
          "width",
          "min-width",
          "max-width",
          "height",
          "min-height",
          "max-height",
          "font-size",
          "font-family",
          "text-align",
          "text-justify",
          "text-indent",
          "text-overflow",
          "text-decoration",
          "white-space",
          "color",
          "background",
          "background-position",
          "background-repeat",
          "background-size",
          "background-color",
          "background-clip",
          "border",
          "border-style",
          "border-width",
          "border-color",
          "border-top-style",
          "border-top-width",
          "border-top-color",
          "border-right-style",
          "border-right-width",
          "border-right-color",
          "border-bottom-style",
          "border-bottom-width",
          "border-bottom-color",
          "border-left-style",
          "border-left-width",
          "border-left-color",
          "border-radius",
          "opacity",
          "filter",
          "list-style",
          "outline",
          "visibility",
          "box-shadow",
          "text-shadow",
          "resize",
          "transition"
        ]

    }
}

Husky && Lint-Staged

  • To perform the git hook when commit and focus on the commit file

  • Update the npm version and install dependencies

npm install -g npm@latest
npm install husky lint-staged
  • Edit the package.json to add prepare script

 // package.json
 "scripts": {
    // run prepare automatically after npm install
    "prepare": "npx husky",
    "dev": "next dev",
    "watch:style": "postcss ./styles/tailwind.css -o ./styles/output.css  -w",
    "build:style": "postcss ./styles/tailwind.css -o ./styles/output.css --env production ",
    "build": "npm run build:style && next build",
    "start": "next start",
    "lint": "eslint src --ext .ts,.tsx .",
    "lint:style": "npx stylelint --fix src/*.scss"
  },
  // set up the configuration of lint-staged
  "lint-staged":{
    "src/**/*.{ts,tsx}": "eslint --fix",
    "src/**/*.scss": "npx stylelint --fix"
  },

  • Can also edit the pre-commit setting in .husky/pre-commit file

// .husky/pre-commit
npx lint-staged --allow-empty

VS Code

  • Close the auto save formatting

  • Edit settings.json of vsCode

{
    "terminal.integrated.shell.osx": "/bin/bash",
    "editor.codeActionsOnSave": {
        "source.fixAll.eslint": true,
        "source.fixAll.stylelint": true
    }
}
  • Edit package.json to delete eslint config (default) and add NPM script to fix the styling problem automatically

 "scripts": {
    "prepare": "husky install",
    "dev": "next dev",
    "watch:style": "postcss ./styles/tailwind.css -o ./styles/output.css  -w",
    "build:style": "postcss ./styles/tailwind.css -o ./styles/output.css --env prodution ",
    "build": "npm run build:style && next build",
    "start": "next start",
    "lint": "eslint src --ext .ts,.tsx .",
    "lint:style": "npx stylelint --fix src/*.scss"
  },

Reference

Setting up Create React App, VS Code, ESLint, and Prettier - Read, Write, Exercise
LogoConfiguring ESLintESLint - Pluggable JavaScript linter
LogoHome | Stylelint
Husky - Git hooks
Logonpm: lint-stagednpm