1. 使用typedoc生成typescript项目文档
针对typescript项目可以使用typedoc来生成文档,typedoc可以全局也可以本项目安装。
npm install typedoc --save-devnpm install typedoc --globaltypedoc --out path/to/documentation/ path/to/typescript/project/
typedoc可以在命令行手动执行,也可以通过 grunt 或者 gulp 实现文档自动化生成。使用gulp实现文档自动化操作可以 参考文章. 使用grunt时则需要通过一个 @vamship/grunt-typedoc 包,需要注意的是,该扩展包是在grunt-typedoc(一个已经失去维护)项目基础上的一个个人仓库,在未来可能并不稳定。目前来说,使用该包之后,在Gruntfile中添加和引入任务,即可通过grunt实现文档任务自动化实现。
grunt.initConfig({typedoc: {build: {options: {module: 'commonjs',out: './docs',name: 'my-project',target: 'ES5'},src: ['./src/**/*']}}});grunt.loadNpmTasks('@vamship/grunt-typedoc');grunt.registerTask('default', ['less','ts','typedoc','watch']);
2. 使用Jest测试typescript项目
Jest支持typescript项目测试,需要先在项目中安装如下依赖
npm install -D jest ts-jest @types/jest
需要在package.json文件中添加测试任务:
{// ..."scripts": {"build": "tsc","test": "jest","test-cov": "jest --coverage"},"jest": {"testEnvironment": "node"},// ...}
需要在项目根目录下新建jest.config.js文件并指定测试参数:
module.exports={roots:["<rootDir>/test"],testRegex: 'test/(.+)\\.test\\.(jsx?|tsx?)$',transform: {"^.+\\.tsx?$": "ts-jest"},moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],};
在项目根目录的test目录下,新建一个index.spec.ts文件,在项目src目录下新建一个index.ts文件:
index.ts文件内容:
/*** This is a TypeScript Starter project* which contains basic less style compile, grunt and jsDoc* @param {msg} userName* @returns a boolean result which always true*/export function hello(msg:string){console.log(`hello ${msg}`);return true;}hello('world');
index.spec.ts文件内容:
/*** index.test.ts*/import {hello} from '../src/index';test('hello world test',()=>{expect(hello('message')).toBe(true);})
运行 npm run test 或者 npm run test-cov 即可实现项目单元测试或覆盖率测试。
本节参考文章
3. 使用 grunt-ts 编译typescript项目
安装grunt-ts模块:
npm install grunt-ts --save-dev
如果之前已经在tsconfig.json文件中设置过tsc命令编译项目typescript的目录和编译参数等内容,那么在Gruntfile中可以指定该配置文件作为ts任务的配置文件,在Gruntfile.js文件中添加ts任务如下,注意,该Gruntfile中的默认任务将less文件编译、typescript文件编译、文档生成和watch热监控集成在了一起按顺序执行,这样可以简化人工工作量:
grunt.initConfig({ts:{default:{tsconfig:'./tsconfig.json'}},});grunt.loadNpmTasks('grunt-ts');grunt.registerTask('default', ['less','ts','typedoc','watch']);
4. Typescript Starter项目
关于本文详细的代码案例可以参考这个TypeScriptStarter项目
