有条件地执行任务

Conditional execution of tasks

我正在创建一个 Gulp 插件,它需要根据插件内生成的条件有条件地执行任务。

根据我的理解,我目前实现的实现条件执行的方法被认为是一种反模式,这是我想避免的。

关于插件

我正在创建的插件捆绑了类似于 Vue 的单个文件组件。插件消化的每个文件在传入的文件内容中查找 DOM 元素,并从这里根据遇到的元素应用修改。下面是一个非常简单的示例,说明传入文件的设置和外观:

你好-world.html

<style>
  .foo { }
</style>

<template>
  Hello World
</template>

<script>
  var foo = 'bar'
  console.log(foo)
</script>

In the example above the plugin would extract contents within the <template></template> tags only and set conditions for the style or script elements.

<script> </script><style> </style> 标签,它们的工作方式略有不同。如果你是 运行 一个构建任务,这些标签将被忽略,但如果 运行 一个监视任务,它们的内容将与缓存副本进行比较,如果检测到更改,将在插件中设置一个条件,例如:sfc.bundleScripts = truesfc.bundleStyles = true.

我设计该插件的方式是,您可以在它们的相关包文件中导入单个文件组件,例如:

styles.scss

@import("components/hello-world.html")

scripts.js

import HelloWorld from 'components/hello-world.html'

这种方法允许我将 <script></script><style></style> 标签的内容捆绑在一起,就好像它们是 .scss.js 文件一样。我通过从插件中调用一个单独的模块来实现这一点,该模块处理从 components/hello-world.html 中检索 <style><script> 标记的内容。

推定的反模式

这让我想到了反模式。我目前在 3 个任务之间建立统一性的方式是 运行 一系列包含 scriptsstyles 任务的单个文件组件任务,例如:


 series(sfc, sfc_Styles, sfc_Styles)

当 运行 处于监视模式时,scripts()styles() 任务在 series() 内调用,但仅根据 sfc.* 条件执行在插件中设置,一个很粗略的例子:


// Basic example of plugin task fn 
function sfc () {
  return src('src/components/*.html')
  .pipe(sfc.bundle())
  .pipe(dest('dest'))
}

// Basic example of conditional execution of styles 
function sfc_Styles () {
  if(sfc.bundleStyles) {
    return styles() // calls the styles task
  } 
}

// Basic example of conditional execution of scripts 
function sfc_Scripts () {
  if(sfc.bundleScripts) {
     scripts() // calls the scripts task
  } 
}

exports.components = series(sfc, sfc_Styles, sfc_Scripts)

这可以吗还是反模式?

所以进一步的挖掘让我得到了以下答案,我将把这些答案作为我目前的方法不是是一个反模式,考虑到 Gulp 4 个任务只是功能。

作为参考,我从Github和Stack中找到了以下答案: