3、环境搭建与工具链:Node.js环境、TypeScript配置、Jest测试框架、ESLint与Prettier
说实话,很多同学学属性验证时,代码写得没问题,但一跑就报错。十有八九是环境没搭对。我见过太多人卡在这一步,明明是个很简单的配置问题,硬是折腾了一整天。
这一章,咱们就把环境彻底搞定。你跟着我一步步来,保证后面写代码时一路畅通。
3.1 Node.js环境:地基要打牢
Node.js是整个工具链的基石。没有它,后面的一切都免谈。
版本选择
我个人习惯用 LTS 版本。为什么?稳定。我在项目中遇到过好几次,用了最新版 Node,结果某个依赖包不兼容,回退版本又得折腾半天。所以,除非你有特殊需求,否则老老实实装 LTS。
安装验证
装完之后,打开终端,敲两行命令确认一下:
node -v
npm -v
能看到版本号,说明 Node 和 npm 都装好了。嗯,这一步很简单,但别跳过。
3.2 TypeScript配置:让代码更靠谱
TypeScript 的好处不用我多说。类型检查、智能提示、代码可读性……说白了,就是让你的代码少出 bug。
初始化项目
先创建一个项目目录,然后初始化:
mkdir formalnode-validation
cd formalnode-validation
npm init -y
接着安装 TypeScript:
npm install typescript --save-dev
生成 tsconfig.json
运行这个命令:
npx tsc --init
它会生成一个默认的配置文件。但默认配置太啰嗦了,我一般会精简成下面这样:
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["ES2020"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}
strict: true— 开启严格模式,这是 TypeScript 的精髓sourceMap: true— 调试时能看到源码,而不是编译后的 JSdeclaration: true— 生成 .d.ts 类型声明文件,方便别人用你的库
目录结构
我习惯这样组织代码:
formalnode-validation/
├── src/
│ ├── index.ts
│ ├── validator.ts
│ └── types.ts
├── tests/
│ └── validator.test.ts
├── dist/
├── tsconfig.json
└── package.json
你想想看,代码和测试分开,编译输出也分开,多清爽。
3.3 Jest测试框架:给代码上保险
写属性验证,最怕的就是改了这里,坏了那里。没有测试,你根本不敢重构。Jest 是我最喜欢的测试框架,没有之一。
安装 Jest 及相关依赖
npm install jest ts-jest @types/jest --save-dev
ts-jest 让 Jest 能直接跑 TypeScript 文件,不用先编译。省事。
配置 Jest
在项目根目录创建 jest.config.js:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
roots: ['/tests'],
testMatch: ['**/*.test.ts'],
moduleFileExtensions: ['ts', 'js', 'json'],
collectCoverage: true,
coverageDirectory: 'coverage',
coverageReporters: ['text', 'lcov'],
coverageThreshold: {
global: {
branches: 80,
functions: 80,
lines: 80,
statements: 80
}
}
};
写第一个测试
在 tests/ 目录下创建 validator.test.ts:
import { validateRequired } from '../src/validator';
describe('validateRequired', () => {
it('should return error when value is empty', () => {
const result = validateRequired('');
expect(result).toEqual({ valid: false, error: '该字段不能为空' });
});
it('should return success when value is provided', () => {
const result = validateRequired('hello');
expect(result).toEqual({ valid: true, error: null });
});
});
跑一下测试:
npx jest
看到绿色的 PASS 了吗?嗯,这就是安全感。
3.4 ESLint与Prettier:代码的颜值担当
代码不仅要能跑,还要好看。ESLint 管逻辑,Prettier 管格式。两者配合,事半功倍。
安装 ESLint
npm install eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
配置 ESLint
创建 .eslintrc.json:
{
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"env": {
"node": true,
"jest": true
},
"rules": {
"@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
"@typescript-eslint/explicit-function-return-type": "warn",
"no-console": "warn"
}
}
no-console 设成 warn 而不是 error。开发时偶尔用 console.log 调试很正常,但上线前记得清理。设成 error 太严格了,反而会让人想关掉 lint。
安装 Prettier
npm install prettier eslint-config-prettier eslint-plugin-prettier --save-dev
配置 Prettier
创建 .prettierrc:
{
"semi": true,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"tabWidth": 2,
"arrowParens": "always"
}
让 ESLint 和 Prettier 和睦相处
在 .eslintrc.json 的 extends 数组最后加上:
"plugin:prettier/recommended"
这样 Prettier 的规则会覆盖 ESLint 中冲突的格式规则。说白了,格式问题听 Prettier 的,逻辑问题听 ESLint 的。
添加 npm scripts
在 package.json 里加上:
"scripts": {
"build": "tsc",
"test": "jest",
"lint": "eslint src/**/*.ts tests/**/*.ts",
"format": "prettier --write src/**/*.ts tests/**/*.ts",
"check": "npm run lint && npm run test && npm run build"
}
以后提交代码前,跑一下 npm run check,三个步骤一次性搞定。我在团队里推行这个做法后,代码 review 的通过率明显提高了。
3.5 知识体系总览
下面这张图,把整个工具链的关系梳理清楚了。你一看就明白:
你看,Node.js 是底座,上面架着 TypeScript、Jest、ESLint+Prettier 三根柱子。它们各自负责一件事,但最终都指向同一个目标:让你能安心地写属性验证代码。
3.6 避坑指南
最后,分享几个我踩过的坑:
- ts-jest 版本不匹配:我曾经升级了 Jest 但忘了升级 ts-jest,结果测试全挂了。记住,这两个版本要对应。
- ESLint 和 Prettier 打架:没加
eslint-config-prettier之前,两个工具互相覆盖规则,代码格式乱成一团。加上就老实了。 - 忘记加 sourceMap:调试时看不到 TypeScript 源码,只能看编译后的 JS,那感觉就像戴着墨镜找眼镜。
- 覆盖率门槛设太低:一开始设个 50%,结果越写越低。后来狠心设到 80%,代码质量明显上来了。
好了,环境搭好了,工具链也配齐了。接下来就可以正式开始写属性验证的逻辑了。你准备好了吗?
公众号:蓝海资料掘金营,微信deep3321