背景介绍

在现代 TypeScript 项目中,高效且规范的开发流程离不开合理的工具链配置。从代码格式化(如 Prettier)到静态类型检查(如 ESLint),再到依赖管理(如 pnpmYarn)和编译优化(如 tsupswc),工具链的合理选择与配置直接影响开发效率、代码质量和团队协作的一致性。

  • 代码格式化:确保团队成员遵循统一的代码风格,减少不必要的格式争议。
  • 静态检查:提前捕获潜在错误,提升代码健壮性。
  • 依赖管理:优化安装速度,减少 node_modules 冗余。
  • 编译优化:加快构建速度,提升开发体验。

目标受众

本文适合以下开发者:

  1. 前端或全栈开发者:使用 TypeScript 进行应用或库开发。
  2. Node.js 技术栈团队:基于 Node.js 构建后端服务或工具链。
  3. 希望优化工程化配置的团队:通过标准化工具提升协作效率。

.npmrc 配置

1
2
3
4
5
6
7
8
9
10
registry=https://registry.npmmirror.com
# 设置缓存目录
cache=.npm/cache
# 设置临时目录
tmp=.npm/tmp
# 设置日志级别
loglevel=error
progress=true
# 优先使用缓存
prefer-offline=true

.prettierrc 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"semi": true,
"trailingComma": "es5",
"singleQuote": false,
"quoteProps": "as-needed",
"printWidth": 100,
"tabWidth": 4,
"useTabs": false,
"arrowParens": "always",
"endOfLine": "lf",
"bracketSpacing": true,
"bracketSameLine": false
}

eslint.config.ts 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import type { Linter } from "eslint";
import { fileURLToPath } from "node:url";
import { dirname } from "node:path";
import js from "@eslint/js";
import tseslint from "typescript-eslint";
import prettierConfig from "eslint-config-prettier";
import prettierPlugin from "eslint-plugin-prettier";

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

export default [
{
ignores: [
"node_modules/**",
"dist/**",
"build/**",
"coverage/**",
"*.config.js",
"*.config.ts",
],
},

js.configs.recommended,
...tseslint.configs.strictTypeChecked,
...tseslint.configs.stylisticTypeChecked,

{
languageOptions: {
parser: tseslint.parser,
parserOptions: {
project: true,
tsconfigRootDir: __dirname,
},
},
plugins: {
"@typescript-eslint": tseslint.plugin,
},
rules: {
// ========== 代码风格 ==========
quotes: ["error", "double", { avoidEscape: true }],
"@typescript-eslint/quotes": ["error", "double"],
"@typescript-eslint/indent": ["error", 4],
"@typescript-eslint/semi": ["error", "always"],
"@typescript-eslint/comma-dangle": ["error", "always-multiline"],

// ========== 类型安全(核心) ==========
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/explicit-function-return-type": [
"error",
{ allowExpressions: true, allowTypedFunctionExpressions: true },
],
"@typescript-eslint/consistent-type-imports": ["error", { prefer: "type-imports" }],

// ========== Promise/异步 ==========
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-misused-promises": "error",
"@typescript-eslint/await-thenable": "error",

// ========== 实用规则 ==========
"@typescript-eslint/no-unused-vars": [
"error",
{ argsIgnorePattern: "^_", varsIgnorePattern: "^_" },
],
"import/no-cycle": "error",

// "no-console": ["warn", { allow: ["warn", "error"] }],
"no-consle": "off",

// ========== 关闭过于严格的规则 ==========
"@typescript-eslint/no-non-null-assertion": "error",
"@typescript-eslint/restrict-template-expressions": "off",
},
},

prettierConfig,
{
plugins: { prettier: prettierPlugin },
rules: {
"prettier/prettier": "error",
"arrow-body-style": "off",
"prefer-arrow-callback": "off",
},
},
] as Linter.Config[];

tsconfig.json 配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
// ============ 模块系统 ============
"module": "NodeNext",
"moduleResolution": "NodeNext",
"target": "ES2022",
"lib": ["ES2022"],

// ============ 文件布局 ============
"rootDir": "./src",
"outDir": "./dist",

// ============ 输出配置 ============
"sourceMap": true,
"declaration": true, // 生成类型声明文件
"declarationMap": true, // 便于 IDE 跳转到源码
"removeComments": true, // 移除注释,减小输出体积

// ============ 严格模式 (推荐全部启用) ============
"strict": true, // 启用所有严格检查
// strict 已包含以下选项,无需重复:
// "noImplicitAny": true,
// "strictNullChecks": true,
// "strictFunctionTypes": true,
// "noImplicitThis": true,
// "alwaysStrict": true,
"strictPropertyInitialization": false, // 确保类的所有实例属性都有明确的初始值

// ============ 额外的严格检查 ============
"noUncheckedIndexedAccess": true, // 数组索引访问返回 T | undefined
"exactOptionalPropertyTypes": false, // 可选属性不允许显式 undefined
"noUnusedLocals": true, // 禁止未使用的局部变量
"noUnusedParameters": true, // 禁止未使用的参数
"noImplicitReturns": true, // 函数必须有返回值
"noFallthroughCasesInSwitch": true, // switch 必须有 break
"noImplicitOverride": true, // 重写方法必须用 override 关键字

// ============ 装饰器支持 ============
"experimentalDecorators": true, // 启用装饰器
"emitDecoratorMetadata": true, // 发出装饰器元数据

// ============ 模块处理 ============
"esModuleInterop": true, // 兼容 CommonJS 和 ES 模块
"allowSyntheticDefaultImports": true, // 允许默认导入
"resolveJsonModule": true, // 允许导入 JSON 文件
"moduleDetection": "force", // 强制所有文件为模块

// ============ 代码质量 ============
"isolatedModules": true, // 确保每个文件可独立编译
"verbatimModuleSyntax": true, // 强制区分类型和值导入
"forceConsistentCasingInFileNames": true, // 强制文件名大小写一致
"skipLibCheck": true, // 跳过库文件检查,加快编译

// ============ 其他优化 ============
"noUncheckedSideEffectImports": true // 防止意外的副作用导入
},

// ============ 别名路径 ============
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@entities/*": ["src/entities/*"],
"@services/*": ["src/services/*"]
},

// ============ 包含和排除 ============
"include": ["src/**/*", "eslint.config.ts"],
"exclude": ["node_modules", "dist", "**/*.spec.ts", "**/*.test.ts", "eslint.config.ts"]
}

文件作用说明

.npmrc:配置npm镜像源和二进制依赖下载地址
.prettierrc:定义代码格式化规则
tsconfig.json:TypeScript编译选项和路径映射
eslint.config.ts:ESLint检查规则(需配合@typescript-eslint插件)

注意事项

  1. 使用前需确保已安装对应依赖包(prettier、typescript、eslint等)
  2. 路径别名(paths)需配合打包工具(如vite/webpack)额外配置
  3. ESLint配置需使用.ts后缀时需要安装@types/eslint类型声明