Improve Frontend Code Quality with Tooling

Improve Frontend Code Quality with Tooling

1月 1, 2019 · 2 分钟阅读时长 · 388 字 · -阅读 -评论

“Messy code makes teammates cry.” Our team felt that pain recently. Refactoring was part of the answer, but we also wanted guardrails that detect issues automatically. This post covers the tools we adopted and how they fit together.

We rely on the following toolbox: EditorConfig, TSLint/ESLint, TypeScript (tsc), Prettier, Husky, and lint-staged.

EditorConfig

Keeps indentation, line endings, and whitespace consistent across editors/OSes. My baseline config:

root = true

[*]
indent_style = space
indent_size = 4
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.md]
trim_trailing_whitespace = false

[*.{css,scss,less,js,jsx,json,ts,tsx,sass,php,html,hbs,mustache,phtml,html.twig}]
indent_size = 2

Install the EditorConfig plugin in your IDE and drop .editorconfig in the project root.

Linting (TSLint → ESLint)

We were midway through a JS → TS migration, so we kept TSLint at the time; ESLint is the modern choice. Lint rules flag style/readability issues in the editor and during builds.

Key points:

  • rules apply to .ts/.tsx; jsRules can mirror them for .js/.jsx during transitions.
  • Most IDEs support “Apply TSLint Code Style Rules” for quick fixes.

TypeScript Compiler (tsc)

Linters don’t catch type errors. Running tsc --noEmit in CI and git hooks surfaces them early. The screenshot below shows an error that TSLint missed but tsc found:

tsc error

Prettier

Prettier handles formatting; lint handles correctness. Example config:

printWidth: 140
singleQuote: true
tabWidth: 2
useTabs: false
arrowParens: avoid
jsxBracketSameLine: false

Install the Prettier IDE plugin, add prettier as a dev dependency, and create .prettierrc.yaml.

Husky + lint-staged

Husky runs scripts during Git hooks. We run tsc and lint-staged on pre-commit:

{
  "hooks": {
    "pre-commit": "tsc --noEmit && lint-staged"
  }
}

lint-staged limits Prettier/TSLint to staged files so commits only touch relevant lines:

"lint-staged": {
  "{,src/**/}*.{ts,tsx,js,jsx}": [
    "tslint --fix",
    "prettier --write"
  ],
  "{,src/**/}*.{md,json,css,scss}": [
    "prettier --write"
  ]
}

IDE Formatting Quirks

Our default “format” shortcut didn’t respect Prettier/TSLint rules (e.g., self-closing JSX tags lost the space). Solution: adjust IDE formatting settings or map a dedicated Prettier hotkey so formatting is consistent.

IDE settings

Takeaways

  • EditorConfig → consistent edits
  • Lint + TypeScript → enforce conventions and catch bugs
  • Prettier → shared formatting baseline
  • Husky + lint-staged → ensure checks run before code lands in main

Investing once in this toolchain pays off every day. It keeps the repository clean so we can focus on building features.

References

Alan H
Authors
开发者,数码产品爱好者,喜欢折腾,喜欢分享,喜欢开源