問題描述
有一個使用 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
這篇關于如何使用打字稿文件運行 gulp的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!