javascript - 如何使用 typescript 文件运行 gulp

标签 javascript typescript configuration compilation gulp

有一个使用 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/

    相关文章:

    maven - "java: package org.junit does not exist"即使它在 Maven pom 中

    javascript - 如何知道用户点击了图像的左侧还是右侧?

    javascript - 将新项目插入数组时出错

    javascript - React-redux 应用程序不会延迟刷新存储

    angular - 如何根据路由参数指定要调用的方法?

    tomcat - 带有 Actuator .war 的 Spring Boot 部署在 tomcat 上

    javascript - jQuery 附加 li 到 ul 无法点击

    reactjs - "No overload matches this call"用于 removeEventListener 和 addEventListener

    typescript - 在项目 .d.ts 定义文件中使用 @types 定义

    java - 如何从jboss数据库配置中获取密码