reboottime / WebDevelopment

Some notes, thoughts and articles aggregated here about UI/UX and web development.
6 stars 0 forks source link

[Frontend Engineering]: Apply Eslint on Vanilla JavaScript code #13

Open reboottime opened 1 year ago

reboottime commented 1 year ago

Abstract

This note tracked why we need eslint and how to use eslint in Valina JavaScript and TypeScript projects.

Background

Why?: People may have different habits and preferences on how to format code and name a variable. While this is not necessarily a problem, team collaboration, codebase maintainability, and readability would be annoying issues when working with other people on a large project.

So here comes a question, how can I enforce a consistent style across team members?

JSLint is the first trial of the above problem. Eslint, a successor, is adopted widely by developers. After typescript adoptions, typescript-eslint project emerged to satisfy the needs of force code style on typescript projects.

reboottime commented 1 year ago

Core concepts in ESlint

To leverage eslint, understanding these core concepts in eslint is critical.

npm init @eslint/config

After a series of guiding steps from the above command, you will get a basic eslint configuration file .eslintrc.cjs under your root folder.

reboottime commented 1 year ago

Some frequently used eslint rules

  1. "multiline-ternary": ["error", "always"],: force breaking ternary into multiple lines
  2. padding-line-between-statements : supported natively by eslint
  3. "typescript-sort-keys": force sort typescript keys in an alphabetized. order

(to be continuted...)

reboottime commented 1 year ago

Format code automatically before commiting code

Though we add eslint configuration files for good intentions, sometimes , people might push code without eslint styling awareness due to eslint is not enabled on vscode.

What if we can reject a git commit if it violates our configured rules? Luckly, git provides a series of Git Hooks (opens new window):

These hooks give us some zone on committing code, let a tool to format our code automatically before commiting code.

Here, we have two tools to implement the desired feature we mentioned above.

reboottime commented 1 year ago

@todo: sort class members https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/member-ordering.md#default-configuration

reboottime commented 1 year ago

References

  1. ESlint official doc
  2. Core concepts in ESLint
  3. what's the difference between ESlint extends and plugins
  4. Husky x LintStaged