如何使用打字稿文件运行 gulp
有一个使用 gulp.js 文件的 gulp 项目,但我的项目在 typescript 中,所以我宁愿在 typescript 中有一个 gulp 文件.可以将过程分为两个步骤,其中我:
1.手动将typescript gulp文件转译成js,然后
2. 调用 gulp <some-task-name>
但这似乎不是最优的.有没有更好的做法这个?
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?
推荐答案
来自 用于转译的 Gulp 文档:
您可以使用需要转译的语言(如 TypeScript 或 Babel)编写 gulpfile,方法是更改 gulpfile.js
上的扩展名以指示语言并安装匹配的转译器模块.
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.
- 对于 TypeScript,重命名为
gulpfile.ts
并安装 ts-node 模块. - 对于 Babel,重命名为
gulpfile.babel.js
并安装 @babel/register 模块.
- 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 支持的更简单方法:
So the simpler way to add TypeScript support in Gulp:
安装
ts-node
,typescript
和 @types/gulp:
$ npm i -D ts-node typescript @types/gulp
如果您有 tsconfig.json
文件,请将 ts-node.compilerOptions.module
设置为 commonjs"
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"
}
}
}
(您不需要 tsconfig.json
文件,这仅适用于您的项目中已经有一个文件)
(You don't need a tsconfig.json
file, this is just for if you have one in your project already)
使用以下演示代码创建 gulpfile.ts
:
Create gulpfile.ts
with the following demo code:
import gulp from 'gulp'; // or import * as gulp from 'gulp'
gulp.task('default', () => console.log('default'));
(或将现有的 Gulpfile.js
重命名为 gulpfile.ts
)
(or rename your existing Gulpfile.js
to 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
相关文章