【问题标题】:The fastest way to Transpile TypeScript in Node在 Node 中转换 TypeScript 的最快方法
【发布时间】:2018-10-20 00:23:23
【问题描述】:

为节点转换 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));
      }
    }

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

【问题讨论】:

  • 不幸的是,您“不能吃蛋糕”。如果你想以某种形式获得转译器的好处,那么你必须付出代价——等待编译。几秒钟是相当快的。消除它的唯一真正方法是不需要转译步骤(例如,只需编写 ES5/6)。如果它有帮助,我们已经在后台运行 WallabyJS(连续测试运行程序)以验证质量并确保没有错误,这有助于减轻对强类型的需求。

标签: javascript node.js typescript gulp


【解决方案1】:
  1. 安装 Nodemon:npm i -g nodemon

  2. 创建文件nodemon.json

    {
     "watch": ["src"],
     "ext": ".ts,.js",
     "ignore": [],
     "exec": "ts-node ./src/server.ts"
    }
    
  3. package.json中添加命令

    "start:dev": "nodemon",
    

【讨论】:

    【解决方案2】:

    更新我的问题 - 只需切换到 `ts-node 如下所示,我就能以更少的行获得快速的结果。

    {
      ...
      "scripts": {
        "start": "ts-node server.ts",
        "dev": "ts-node-dev --respawn --transpileOnly server.ts",
        "test": "./node_modules/.bin/mocha --compilers ts:ts-node/register ./test/**/**/**/*.ts",
      },
      ...
    }
    

    package.json 内容,更多https://github.com/ivanproskuryakov/express-typescript-boilerplate

    【讨论】:

      【解决方案3】:

      您是否尝试过 tsc --watch 中间没有 gulp 或 npm ?这就是我发现的最快的方式来观察和编译我的项目。第一次需要 1 - 2 秒 - 但随后几乎是瞬间的。如果您的目标是尽可能快,那么您可以摆脱所有技术 - 即使 npm 也需要半秒 - 我想 gulp 更多。

      另外,另一方面,如果您正在处理多个 typescript 项目,请确保您使用的是新的 TypeScript 功能 Composite 项目,https://www.typescriptlang.org/docs/handbook/project-references.html - 在我的情况下,我正在使用 mono-repo 和几个项目需要编译,此功能大大提高了速度并简化了编译工作流程。

      请记住,TypeScript 不仅仅是一个编译器,它还是一个语言服务 - 这就是为什么 -watch 比 tsc 做得更好 - 它会执行部分编译

      【讨论】:

      • 第一次运行需要 1-2 秒,在随后的运行中非常快,因为它使用增量编译。似乎最近的 webpack 插件已经利用了这一点,我不能对 gulp 插件说同样的话,因为它们可能已经过时了。
      • 是的,这就是 tsc 的美妙之处——看它在第一次之后是增量的。为什么要让 webpack 参与调试?如果目的是尽可能快地调试单元测试,我强烈建议使用最少数量的技术。连 npm 都会加半秒……我的两分钱
      • 我提到 webpack 只是作为一个例子“即使使用 webpack 编译速度也很快”。
      猜你喜欢
      • 2022-08-15
      • 2010-11-17
      • 2019-07-15
      • 2011-04-30
      • 1970-01-01
      • 2019-06-23
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多