背景介绍

在现代 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
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# ============ 镜像源 ============
# 设置 npm 镜像源为国内镜像,提高安装速度
registry=https://registry.npmmirror.com

# ============ 缓存和临时目录 ============
# 设置 npm 缓存目录,避免污染项目目录
cache=.npm/cache
# 设置 npm 临时文件目录
tmp=.npm/tmp
# 设置缓存的最小有效期(秒),避免频繁网络请求
cache-min=86400

# ============ 日志与进度 ============
# 设置日志级别为 error,减少无用日志输出
loglevel=error
# 安装或下载包时显示进度条
progress=true

# ============ 离线优化 ============
# 优先使用缓存中的包,减少网络请求
prefer-offline=true
# 可选:完全离线模式(需要缓存完整)
# offline=true

# ============ 依赖管理 ============
# 安装依赖时锁定确切版本号,避免出现 ^ 或 ~ 引入的非预期更新
save-exact=true
# 始终生成 package-lock.json 文件,确保团队一致性
package-lock=true
# 安装依赖时跳过可选依赖
optional=false

.prettierrc.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
{
// 语句末尾是否加分号
"semi": true,

// 尾随逗号设置为 none
"trailingComma": "none",

// 是否使用单引号
"singleQuote": false,

// 对象属性加引号的策略
"quoteProps": "as-needed",

// 每行最大长度
"printWidth": 100,

// 缩进宽度
"tabWidth": 4,

// 是否使用 tab
"useTabs": false,

// 箭头函数参数是否总带括号
"arrowParens": "always",

// 换行符类型
"endOfLine": "lf",

// 对象花括号内是否有空格
"bracketSpacing": true,

// 多行 JSX 的闭合标签是否在同一行
"bracketSameLine": false
}

.eslintrc.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
71
72
73
74
75
76
77
78
{
// 声明为根配置,防止向上继承
"root": true,

// 环境配置
"env": {
"browser": true, // 浏览器全局变量
"node": true, // Node.js 全局变量
"es2021": true // 启用 ES2021 全局变量
},

// 继承推荐规则
"extends": [
"eslint:recommended", // ESLint 官方推荐规则
"plugin:@typescript-eslint/recommended", // TypeScript 推荐规则
"plugin:@typescript-eslint/recommended-requiring-type-checking", // 严格类型检查规则
"plugin:prettier/recommended" // 集成 Prettier,关闭冲突规则
],

// 使用 TypeScript 解析器
"parser": "@typescript-eslint/parser",

// 解析器选项
"parserOptions": {
"ecmaVersion": "latest", // 支持最新 ECMAScript
"sourceType": "module", // 使用 ES 模块
"project": "./tsconfig.json" // TypeScript 项目配置文件
},

// 插件
"plugins": ["@typescript-eslint", "prettier"],

// 自定义规则
"rules": {
// ========== 代码风格 ==========
"quotes": ["error", "double", { "avoidEscape": true }], // 双引号,允许转义
"@typescript-eslint/quotes": ["error", "double"],
"@typescript-eslint/indent": ["error", 4], // 缩进 4 空格
"@typescript-eslint/semi": ["error", "always"], // 语句末尾必须分号
"@typescript-eslint/comma-dangle": ["error", "never"], // 多行尾随逗号

// ========== 类型安全 ==========
"@typescript-eslint/no-explicit-any": "error", // 禁止 any
"@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", // 禁止未处理的 Promise
"@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": "off", // 允许 console
"@typescript-eslint/no-non-null-assertion": "error", // 禁止非空断言
"@typescript-eslint/restrict-template-expressions": "off", // 放宽模板字符串限制

// ========== Prettier ==========
"prettier/prettier": "error" // Prettier 格式错误报错
},

// 忽略文件
"ignorePatterns": [
"node_modules/**",
"dist/**",
"build/**",
"coverage/**",
"*.config.js",
"*.config.ts"
]
}

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
{
"$schema": "https://json.schemastore.org/tsconfig",

// ============ 编译选项 ============
"compilerOptions": {
// ============ 模块系统 ============
"module": "NodeNext", // 使用 Node.js ESM 模块
"moduleResolution": "NodeNext", // 模块解析策略
"target": "ES2022", // 编译目标 ES2022
"lib": ["ES2022"], // 可用标准库

// ============ 文件布局 ============
"rootDir": "./src", // 源码根目录
"outDir": "./dist", // 编译输出目录

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

// ============ 严格模式 ============
"strict": true, // 启用所有严格检查
"strictPropertyInitialization": false, // 不强制类属性初始化

// ============ 额外严格检查 ============
"noUncheckedIndexedAccess": true, // 数组索引可能返回 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.json:定义代码格式化规则
tsconfig.json:TypeScript编译选项和路径映射
.eslintrc.json:ESLint检查规则(需配合@typescript-eslint插件)

注意事项

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