在Node中使用Transpile TypeScript的最快方法

iva*_*kov 6 javascript node.js typescript gulp

为节点转换Typescript的最佳(实时?)方法是什么?

我正在使用WebStorm并在后台运行gulp任务backend:watch来监听更改.因此,当我在WebStorm中点击"保存"时,它确实将TS转换为JS并存储在/build目录下.

我的方法效果很好,但是转换是耗时的 - 每次运行需要两到三秒,秒会变成分钟,依此类推.

有没有办法优化它,一个更好的选择?

  • https://www.npmjs.com/package/ts-node是另一种选择,但我不确定它比我现在拥有的更好.
  • 另外,听说基于Electron的新VisualStudio很好,但它将JS文件保存在同一个位置,对我来说看起来不整洁.

    //////////////////////////////////////////////
    // Backend tasks
    //////////////////////////////////////////////
    
    const appSourceDir = path.join(dir, '/app');
    const appSourceGlob = `${appSourceDir}/**/*.*`;
    const appSourceRelativeGlob = 'app/**/*.*';
    const appCodeGlob = `${appSourceDir}/**/*.ts`;
    const appCodeRelativeGlob = 'app/**/*.ts';
    const appFilesGlob = [appSourceGlob, `!${appCodeGlob}`];
    const appFilesRelativeGlob = [appSourceRelativeGlob, `!${appCodeRelativeGlob}`];
    const appBuildDir = path.join(dir, '/build');
    
    
    gulp.task('backend:symlink', [], function (done) {
      const appTargetDir = path.join(dir, '/node_modules/app');
      // symlink for app
      fs.exists(appTargetDir, function (err) {
        if (!err) {
          fs.symlinkSync(appBuildDir, appTargetDir, 'dir');
        }
      });
    
      done();
    });
    
    gulp.task('backend:clean', function (done) {
      clean([appBuildDir + '/**/*', '!.gitkeep'], done);
    });
    
    gulp.task('backend:compile', function (done) {
      tsCompile([appCodeGlob], appBuildDir, appSourceDir, done);
    });
    
    gulp.task('backend:files', function () {
      // copy fixtures and other non ts files
      // from app directory to build directory
      return gulp
        .src(appFilesGlob)
        .pipe(plugin.cached('files'))
        .pipe(gulp.dest(appBuildDir));
    });
    
    gulp.task('backend:build', function (done) {
      sequence(
        'backend:clean',
        'backend:compile',
        'backend:files',
        done
      );
    });
    
    gulp.task('backend:watch:code', function () {
      const watcher = gulp.watch([appCodeRelativeGlob], ['backend:compile']);
    
      watcher.on('change', function (event) {
        // if a file is deleted, forget about it
        if (event.type === 'deleted') {
          // gulp-cached remove api
          delete plugin.cached.caches.code[event.path];
          delete plugin.event.caches.lint[event.path];
          // delete in build
          del(getPathFromSourceToBuild(event.path, appSourceDir, appBuildDir));
        }
      });
    });
    
    gulp.task('backend:watch:files', function () {
      const watcher = gulp.watch([appFilesRelativeGlob], ['backend:files']);
    
      watcher.on('change', function (event) {
        // if a file is deleted, forget about it
        if (event.type === 'deleted') {
          // gulp-cached remove api
          delete plugin.cached.caches.files[event.path];
          delete plugin.event.caches.lint[event.path];
          // delete in build
          del(getPathFromSourceToBuild(event.path, appSourceDir, appBuildDir));
        }
      });
    });
    
    gulp.task('backend:watch', ['backend:build'], function (done) {
      // first time build all by backend:build,
      // then compile/copy by changing
      gulp
        .start([
          'backend:watch:code',
          'backend:watch:files'
        ], done);
    });
    
    //////////////////////////////////////////////
    // Helpers
    //////////////////////////////////////////////
    
    /**
     * remaps file path from source directory to destination directory
     * @param {string} file path
     * @param {string} source directory path
     * @param {string} destination directory path
     * @returns {string} new file path (remapped)
     */
    function getPathFromSourceToBuild(file, source, destination) {
      // Simulating the {base: 'src'} used with gulp.src in the scripts task
      const filePathFromSrc = path.relative(path.resolve(source), file);
      // Concatenating the 'destination' absolute
      // path used by gulp.dest in the scripts task
      return path.resolve(destination, filePathFromSrc);
    }
    
    /**
     * @param  {Array}    path - array of paths to compile
     * @param  {string}   dest - destination path for compiled js
     * @param  {string}   baseDir - base directory for files compiling
     * @param  {Function} done - callback when complete
     */
    function tsCompile(path, dest, baseDir, done) {
      const ts = plugin.typescript;
      const tsProject = ts.createProject('tsconfig.json');
    
      gulp
        .src(path, {base: baseDir})
        // used for incremental builds
        .pipe(plugin.cached('code'))
        .pipe(plugin.sourcemaps.init())
        .pipe(tsProject(ts.reporter.defaultReporter())).js
        .pipe(plugin.sourcemaps.write('.'))
        .pipe(gulp.dest(dest))
        .on('error', done)
        .on('end', done);
    }
    
    /**
     * Delete all files in a given path
     * @param  {Array}   path - array of paths to delete
     * @param  {Function} done - callback when complete
     */
    function clean(path, done) {
      log('Cleaning: ' + plugin.util.colors.blue(path));
      del(path).then(function (paths) {
        done();
      });
    }
    
    /**
     * Log a message or series of messages using chalk's blue color.
     * Can pass in a string, object or array.
     */
    function log(msg) {
      if (typeof (msg) === 'object') {
        for (let item in msg) {
          if (msg.hasOwnProperty(item)) {
            plugin.util.log(plugin.util.colors.blue(msg[item]));
          }
        }
      } else {
        plugin.util.log(plugin.util.colors.blue(msg));
      }
    }
Run Code Online (Sandbox Code Playgroud)

也发布在GitHub上,请参阅https://github.com/ivanproskuryakov/loopplate-node.js-boilerplate

can*_*ero 11

你是不是在tsc --watch没有gulp的情况下尝试也不是在中间的npm?这就是我发现观察和编译项目的最快方法.它第一次需要1-2秒 - 但几乎是瞬间的.如果你的目标是尽可能快地摆脱所有技术 - 甚至npm将需要半秒 - 我想更多.

另外,另一方面,如果您正在使用多个打字稿项目,请确保您使用新的TypeScript功能复合项目,https://www.typescriptlang.org/docs/handbook/project-references.html - 在我的case我正在使用mono-repo,需要编译几个项目,这个功能可以大大提高速度并简化编译工作流程.

请记住,TypeScript不仅仅是一个编译器,它也是一个语言服务 - 这就是为什么-watch将比tsc更好地完成工作 - 它将执行部分编译