1. 使用typedoc生成typescript项目文档

针对typescript项目可以使用typedoc来生成文档,typedoc可以全局也可以本项目安装。

  1. npm install typedoc --save-dev
  2. npm install typedoc --global
  3. typedoc --out path/to/documentation/ path/to/typescript/project/

typedoc可以在命令行手动执行,也可以通过 grunt 或者 gulp 实现文档自动化生成。使用gulp实现文档自动化操作可以 参考文章. 使用grunt时则需要通过一个 @vamship/grunt-typedoc 包,需要注意的是,该扩展包是在grunt-typedoc(一个已经失去维护)项目基础上的一个个人仓库,在未来可能并不稳定。目前来说,使用该包之后,在Gruntfile中添加和引入任务,即可通过grunt实现文档任务自动化实现。

  1. grunt.initConfig({
  2. typedoc: {
  3. build: {
  4. options: {
  5. module: 'commonjs',
  6. out: './docs',
  7. name: 'my-project',
  8. target: 'ES5'
  9. },
  10. src: ['./src/**/*']
  11. }
  12. }
  13. });
  14. grunt.loadNpmTasks('@vamship/grunt-typedoc');
  15. grunt.registerTask('default', ['less','ts','typedoc','watch']);

2. 使用Jest测试typescript项目

Jest支持typescript项目测试,需要先在项目中安装如下依赖

  1. npm install -D jest ts-jest @types/jest

需要在package.json文件中添加测试任务:

  1. {
  2. // ...
  3. "scripts": {
  4. "build": "tsc",
  5. "test": "jest",
  6. "test-cov": "jest --coverage"
  7. },
  8. "jest": {
  9. "testEnvironment": "node"
  10. },
  11. // ...
  12. }

需要在项目根目录下新建jest.config.js文件并指定测试参数:

  1. module.exports={
  2. roots:[
  3. "<rootDir>/test"
  4. ],
  5. testRegex: 'test/(.+)\\.test\\.(jsx?|tsx?)$',
  6. transform: {
  7. "^.+\\.tsx?$": "ts-jest"
  8. },
  9. moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
  10. };

在项目根目录的test目录下,新建一个index.spec.ts文件,在项目src目录下新建一个index.ts文件:
index.ts文件内容:

  1. /**
  2. * This is a TypeScript Starter project
  3. * which contains basic less style compile, grunt and jsDoc
  4. * @param {msg} userName
  5. * @returns a boolean result which always true
  6. */
  7. export function hello(msg:string){
  8. console.log(`hello ${msg}`);
  9. return true;
  10. }
  11. hello('world');

index.spec.ts文件内容:

  1. /**
  2. * index.test.ts
  3. */
  4. import {hello} from '../src/index';
  5. test('hello world test',()=>{
  6. expect(hello('message')).toBe(true);
  7. })

运行 npm run test 或者 npm run test-cov 即可实现项目单元测试或覆盖率测试。
本节参考文章

3. 使用 grunt-ts 编译typescript项目

安装grunt-ts模块:

  1. npm install grunt-ts --save-dev

如果之前已经在tsconfig.json文件中设置过tsc命令编译项目typescript的目录和编译参数等内容,那么在Gruntfile中可以指定该配置文件作为ts任务的配置文件,在Gruntfile.js文件中添加ts任务如下,注意,该Gruntfile中的默认任务将less文件编译、typescript文件编译、文档生成和watch热监控集成在了一起按顺序执行,这样可以简化人工工作量:

  1. grunt.initConfig({
  2. ts:{
  3. default:{
  4. tsconfig:'./tsconfig.json'
  5. }
  6. },
  7. });
  8. grunt.loadNpmTasks('grunt-ts');
  9. grunt.registerTask('default', ['less','ts','typedoc','watch']);

本节参考文章

4. Typescript Starter项目

关于本文详细的代码案例可以参考这个TypeScriptStarter项目