1 代码检查

代码检查主要是用来发现代码错误、统一代码风格。JavaScript 中常用 ESLint 进行类型检查,同样 TypeScript 也使用 ESLint 进行类型检查,但 TypeScript 还需要额外的支持 TypeScript 语法的插件 @typescript-eslint/parser@typescript-eslint/eslint-plugin 等,

1.1 使用 typescript-eslint

先安装
npm i -D typescript-eslint typescript eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
然后配置 .eslintrc.js 文件:

  1. // .eslintrc.js
  2. module.exports = {
  3. parser: '@typescript-eslint/parser',
  4. plugins: ['@typescript-eslint'],
  5. rules: {
  6. // 禁止使用 var
  7. 'no-var': "error",
  8. // 优先使用 interface 而不是 type
  9. '@typescript-eslint/consistent-type-definitions': [
  10. "error",
  11. "interface"
  12. ]
  13. }
  14. }

2 使用 Prettier 统一编码风格

VSCode 中安装插件 Prettier ,并配置 .prettierrc.js 文件,进而统一编码风格

  1. // prettier.config.js or .prettierrc.js
  2. module.exports = {
  3. // 一行最多 100 字符
  4. printWidth: 100,
  5. // 使用 4 个空格缩进
  6. tabWidth: 4,
  7. // 不使用缩进符,而使用空格
  8. useTabs: false,
  9. // 行尾需要有分号
  10. semi: true,
  11. // 使用单引号
  12. singleQuote: true,
  13. // 对象的 key 仅在必要时用引号
  14. quoteProps: 'as-needed',
  15. // jsx 不使用单引号,而使用双引号
  16. jsxSingleQuote: false,
  17. // 末尾不需要逗号
  18. trailingComma: 'none',
  19. // 大括号内的首尾需要空格
  20. bracketSpacing: true,
  21. // jsx 标签的反尖括号需要换行
  22. jsxBracketSameLine: false,
  23. // 箭头函数,只有一个参数的时候,也需要括号
  24. arrowParens: 'always',
  25. // 每个文件格式化的范围是文件的全部内容
  26. rangeStart: 0,
  27. rangeEnd: Infinity,
  28. // 不需要写文件开头的 @prettier
  29. requirePragma: false,
  30. // 不需要自动在文件开头插入 @prettier
  31. insertPragma: false,
  32. // 使用默认的折行标准
  33. proseWrap: 'preserve',
  34. // 根据显示样式决定 html 要不要折行
  35. htmlWhitespaceSensitivity: 'css',
  36. // 换行符使用 lf
  37. endOfLine: 'lf'
  38. };

3 编译选项

TypeScript 提供了非常多的编译配置选项

选项 类型 默认值 说明
allowJs boolean false 允许编译 JavaScript (通常在混编时开启)
allowSyntheticDefaultImports boolean false 允许对不含默认导出的模块使用默认导入