javascript - 如何编写一个使用其他 gulp 插件的 gulp 插件?

标签 javascript gulp

我有一个预编译 Handlebars 模板的 gulp 任务,它包含以下内容:

gulp.src(['templates/*.hbs'])
    .pipe(handlebars())
    .pipe(declare({
      namespace: 'Template.templates',
      noRedeclare: true
    }))
    .pipe(concat('compiled.js'))
    .pipe(header('Template = {};\nTemplate.render = function(templateName, context) { return Handlebars.template(Template.templates[templateName])(context) };\n'))
    .pipe(gulp.dest('templates'));

我想创建一个包装此功能的 gulp 插件以使其更易于使用,如下所示:

gulp.src(['templates/*.hbs'])
  .pipe(handlebars2())
  .dest('templates')

或者有选项:

gulp.src(['templates/*.hbs'])
  .pipe(handlebars2({
    filename: 'compiled.js',
    namespace: 'Template'
  }))
  .dest('templates')

编写 gulp 插件的文档和我看过的示例源代码只显示了流的用法,我不确定如何应用它来利用我自己的其他 gulp 插件。

我如何编写一个 gulp 插件来完成上述 handlebars2 的功能?

即使有人只是给我指出了正确的方向,我也可以解决它并将解决方案发布为其他人的答案。谢谢!

最佳答案

gulp 插件所做的是返回一个流,该流将使用来自另一个流的数据:

readable.pipe(writable);

当您尝试制作一个 gulp 插件时,您无法直接访问您正在读取的流。您只能访问它传递给您的数据(例如乙烯基文件)。

这样你就不能以传统的方式传递给它。您要做的是重用部分管道。

要轻松实现这样的事情,请尝试使用 lazypipe:

var lazypipe = require('');

var handlebars2 = lazypipe()  
    .pipe(handlebars)
    .pipe(declare,{
      namespace: 'Template.templates',
      noRedeclare: true
    })
    .pipe(concat,'compiled.js')
    .pipe(header,'Template = {};\nTemplate.render = function(templateName, context) { return Handlebars.template(Template.templates[templateName])(context) };\n');

切记不要在这里调用流创建函数,lazypipe 会为您调用它们。

希望我帮到了你。

关于javascript - 如何编写一个使用其他 gulp 插件的 gulp 插件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25343197/

相关文章:

javascript - ReactJS 中的路由。 URL已显示,但组件未呈现

javascript - 在javascript中将java列表转换为数组

javascript - JQuery 日期选择器在刷新时不显示

javascript - 如何在 Istanbul 尔覆盖 React jsx 文件?

javascript - 任务 'sass' 不在您的 Gulpfile 中 - 错误

twitter-bootstrap-3 - 无法使用 SASS、Laravel 5 和 Elixir/Gulp 自定义 Twitter Bootstrap

javascript - Ruby on Rails 使用静态脚本文件在 View 中渲染

javascript - Electron require() 未定义

javascript - ReferenceError : require is not defined in ES module scope, 你可以使用 import 代替 gulp sass

html - 在 CSS 而不是 HTML 中组合类