javascripttypescriptconfigurationcompilationgulp

How can I run gulp with a typescript file


Have a gulp project that uses a gulp.js file but my project is in typescript so I'd rather have a gulp file in typescript. It would be possible to break the process into two steps where I:

1. Manually transpile the typescript gulp file into js, then
2. Call gulp <some-task-name>

But that doesn't seem optimal. Is there any better way of doing this?


Solution

  • From Gulp docs for transpilation:

    Transpilation

    You can write a gulpfile using a language that requires transpilation, like TypeScript or Babel, by changing the extension on your gulpfile.js to indicate the language and install the matching transpiler module.

    • For TypeScript, rename to gulpfile.ts and install the ts-node module.
    • For Babel, rename to gulpfile.babel.js and install the @babel/register module.

    So the simpler way to add TypeScript support in Gulp:

    1. Install ts-node, typescript, and @types/gulp:

      $ npm i -D ts-node typescript @types/gulp
      
    2. If you have a tsconfig.json file set ts-node.compilerOptions.module to "commonjs"

      {
          // these options are overrides used only by ts-node 
          "ts-node": {
              "compilerOptions": {
                  "module": "commonjs" 
              }
          }
      }
      

      (You don't need a tsconfig.json file, this is just for if you have one in your project already)

    3. Create gulpfile.ts with the following demo code:

      import gulp from 'gulp'; // or import * as gulp from 'gulp'
      gulp.task('default', () => console.log('default'));
      

      (or rename your existing Gulpfile.js to gulpfile.ts)

    4. Start the build:

      $ npx gulp
      

    The output should look similar to this:

    $ gulp
    [21:55:03] Requiring external module ts-node/register
    [21:55:03] Using gulpfile ~/src/tmp/typescript-tmp/gulpfile.ts
    [21:55:03] Starting 'default'...
    default
    [21:55:03] Finished 'default' after 122 μs