node.js - gulp 中的任务继承,父级 gulpfile.js

标签 node.js npm gulp

我正在使用 node/gulp 来运行/构建我的项目。在这些项目中,我的 gulpfiles 看起来非常相似。因为我有 Java/Maven 背景,所以我一直在寻找某种东西。就像父 gulpfile 一样,我们可以继承基本任务(这可以通过 maven 中的父 pom.xml 轻松实现)。

这是否以某种方式构建到 gulp 中,是否有模块执行此操作,或者我需要自己解决这个问题?

我可以考虑让一个 Node 模块不做任何其他事情,然后提供可以从其依赖的 gulp 文件中需要的基本 gulp 任务。有类似方法的经验吗?

BR 克里斯

最佳答案

您可以在父 gulp 文件中导出 gulp 对象,然后在子 gulp 文件中引用它:

project/gulpfile.js:

var gulp = require('gulp');

gulp.task('commontask', function () { });

module.exports = gulp;

项目/子项目/gulpfile.js:

var gulp = require('../gulpfile.js');

gulp.task('subtask', [ 'commontask' ], function() { });

project/subproject 目录运行 subtask:

> gulp subtask
[12:38:05] Using gulpfile ~/project/subproject/gulpfile.js
[12:38:05] Starting 'commontask'...
[12:38:05] Finished 'commontask' after 50 μs
[12:38:05] Starting 'subtask'...
[12:38:05] Finished 'subtask' after 20 μs

编辑:如果父 gulpfile 不是同一包的一部分(例如 my-app),而是来自您创建的另一个包,则上述内容将不起作用取决于(例如my-common-tasks)。原因是 Node.js 中模块加载的工作方式,最终会得到两个 gulp 实例:一个位于 my-common-tasks 中,另一个位于 我的应用程序。您的任务将在 my-common-tasks 的实例中定义,但 gulp CLI 将在 my-app 的实例中查找任务.

相反,您必须将 gulp 实例从 my-app 传递到 my-common-tasks:

my-common-tasks/gulpfile.js:

module.exports = function(gulp) {
  gulp.task('common-task', function () { });
};

my-app/gulpfile.js:

var gulp = require('gulp');
require('my-common-tasks')(gulp);

gulp.task('sub-task', [ 'common-task' ], function() { });

关于node.js - gulp 中的任务继承,父级 gulpfile.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36198562/

相关文章:

node.js - Windows 10 Electronic-Packager期间缺少ELECTRON.EXE

node.js - 如何生成Semantic UI离线文档

javascript - 当我创建一个新项目时,angular 7 不会询问是否使用路由

javascript - Gulp Concat 没有输出文件

javascript - 如何将 watch 添加到 gulp 中的文件夹中

javascript - 如何使用对象列表作为 gulp 源流

node.js - 如何将 Node Date()插入到postgresql时间戳列中?

sql - 数据设置为 json with group

node.js - Node js 应用程序在 Windows 计算机中给出错误 "%1 is not a valid Win32 application"

c# - 如何在 ASP.NET Core 中使用 npm