網站搜尋

TypeScript 編譯建議 (TS + gulp + karma)


我正在嘗試提出一個可行的 TypeScript 建置步驟,其中包括以下內容:

  • 編譯 TypeScript(顯然)

    • 理想情況下允許編譯器遍歷依賴樹
  • 通過 Karma 執行 Jasmine 單元測試
  • 執行測試和輸出 JS 不依賴任何 IDE(Visual Studio/WebStorm)
  • 透過 WebStorm 的運行配置來執行單元測試的能力
  • 程式碼覆蓋率結果是基於 TS 程式碼,而非生成的 JS

我目前的嘗試涉及使用:

  • gulp-tsc
  • 業力
  • karma-typescript 預處理器

我希望只需要執行一次編譯步驟,因為目前我必須為單元測試執行預編譯步驟,並且為輸出到我的 dist 資料夾執行下方的 build-ts 步驟。我曾嘗試使用 karma-typescript-pre-processor,但效果不一且性能不佳(執行測試時 16 秒,未執行測試時 2 秒)。

注意:我尚未嘗試處理程式碼覆蓋率的部分,因為我對目前的建置/單元測試解決方案不滿意。

我目前使用的 karma 檔案是

module.exports = function(config) {
  config.set({
    browsers: ['PhantomJS'],
    frameworks: ['jasmine'],
    files: [
      '../bower_components/angular/angular.js',
      '../bower_components/angular-mocks/angular-mocks.js',
      '../app/**/*_test.ts',
      {
        pattern: '../app/**/!(*_test).ts',
        included: false
      }
    ],
    preprocessors: {
      '../typings/jasmine/jasmine.d.ts': ['typescript'],
      '../app/**/*.ts': ['typescript']
    },
    typescriptPreprocessor: {
      options: {
        sourceMap: true,
        target: 'ES5',
        noResolve: false
      },
      transformPath: function(path) {
        return path.replace(/\.ts$/, '.js');
      }
    },
    //reporters: ['progress', 'growl'],
    colors: true
  });
};

gulpfile :

gulp.task('build-ts', function () {
  return gulp.src(paths.ts)
    .pipe(tsc({
      noResolve: false,
      out: 'app.js',
      outDir: paths.dist.js,
      removeComments: true,
      //sourcePath: '../../app/ts',
      //sourcemap: true,
      target: 'ES5'
    }))
    .pipe(gulp.dest(paths.dist.js))
    .pipe(connect.reload());
});

答案#1

你可以使用 gulp.watch 在每次保存時編譯 TypeScript 文件。這樣當你運行測試時,TypeScript 已經被編譯。gulp-tsc 模組應該有關於設置增量編譯的指南。