有一个使用 gulp.js 文件的 gulp 项目,但我的项目在 typescript 中,所以我宁愿在 typescript 中有一个 gulp 文件。可以将过程分为两个步骤,其中我:
1.手动将typescript gulp文件转译成js,然后
2. 调用gulp <some-task-name>
但这似乎不是最优的。有没有更好的做法
这个?
最佳答案
来自 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.
因此,在 Gulp 中添加 TypeScript 支持的更简单方法是:
ts-node
, typescript
, 和 @types/gulp :$ npm i -D ts-node typescript @types/gulp
tsconfig.json
文件集ts-node.compilerOptions.module
至"commonjs"
{
// these options are overrides used only by ts-node
"ts-node": {
"compilerOptions": {
"module": "commonjs"
}
}
}
(您不需要 tsconfig.json
文件,这仅适用于您的项目中已经有一个文件)gulpfile.ts
使用以下演示代码:import gulp from 'gulp'; // or import * as gulp from 'gulp'
gulp.task('default', () => console.log('default'));
(或将现有的 Gulpfile.js
重命名为 gulpfile.ts
)$ npx gulp
输出应与此类似:
$ 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
关于javascript - 如何使用 typescript 文件运行 gulp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49847926/