这篇文章上次修改于 857 天前,可能其部分内容已经发生变化,如有疑问可询问作者。
1 初始化 typescript 项目
mkdir demo-ts
cd demo-ts
yarn init
yarn add typescript
npx tsc --init创建文件:
mkdir src
touch src/index.ts写入如下内容:
'use strict';
const hello = (world: string) => {
console.log(`hello ${world}`);
}
hello('world');执行:
ts-node src/index.ts添加 .gitignore 文件:
npx gitignore node2 添加测试
yarn add --dev jest ts-jest @types/jest
npx ts-jest config:init添加测试命令,在 package.json 中添加:
"scripts": {
"test": "jest"
},创建 __test__ 文件夹,并添加测试文件,必须以 test.ts 结尾,写入如下内容:
import { add, multiply } from "../src/math";
describe("Math functions", () => {
it("should multiply 5 by 3", () => {
const result = multiply(5, 3);
expect(result).toEqual(15);
});
it("should add 5 by 3", () => {
const result = add(5, 3);
expect(result).toEqual(8);
});
});运行测试:
yarn run test3 格式化
yarn add --dev prettier在 package.json 中添加:
"scripts": {
...
"format": "prettier -wu src/*"
},然后运行:
yarn run format也可以创建自定义的格式配置文件 .prettierrc
4 Git 集成
有两种方式
git add 的时候自动格式化
yarn add --dev pre-commit在 package.json 中添加:
"scripts": {
...
"format": "prettier -wu src/*"
},
"pre-commit": ["format"],git commit 的时候自动格式化
yarn add --dev mrm@2
npx mrm lint-staged参考
Unit testing TypeScript with Jest: Part One — Project setup
代码美化神器——Prettier使用详解


没有评论