How can I run gulp with a typescript file
In case anyone else runs into this, @tony19's answer above will only work for some projects ;-)
import * as gulp from 'gulp';
won't always work (it depends on your tsconfig.json settings- specifically allowSyntheticDefaultImports
), the "safer" thing to use is import gulp from 'gulp';
which should work regardless of the allowSyntheticDefaultImports
value.
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:
Install
ts-node
,typescript
, and @types/gulp:$ npm i -D ts-node typescript @types/gulp
If you have a
tsconfig.json
file setts-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)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
togulpfile.ts
)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
Set up a gulp.js
file in the root of your project with nothing but the following line.
eval(require('typescript').transpile(require('fs').readFileSync("./gulp.ts").toString()));
Then create another actual gulp file written in typescript in a file gulp.ts
. What will happen is that the gulp.js
file will be loaded but will bootstrap the process by compiling your `gulp.ts' file and passing the transpiled results instead.
This allows us to not have to precompile the gulp.ts file before using it. Instead you can just type gulp test
and it will be executed from your tyepscript file without any extra calls.
- Make sure to run the following first:
npm install typescript --save-dev
npm install fs --save-dev