需要gulpfile中的另一个文件(不在node_modules中) [英] Require another file in gulpfile (which isn't in node_modules)

查看:132
本文介绍了需要gulpfile中的另一个文件(不在node_modules中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用gulp一段时间,并知道如何导入另一个节点模块,例如

I've been using gulp for a while now and know how to import another node module, e.g.

var sass = require('gulp-sass');

没问题,但是我的gulpfile填满了代码,我想将其移入单独的文件和要求。具体来说,我正在写一个postcss插件,我已经在gulpfile中声明为函数时工作了。我的问题是如何把我的功能放在一个外部文件中,并需要它像我做一个节点模块。我是否需要导出所需文件中的功能?我需要使用ES6模块或类似的东西吗?

That's fine, but my gulpfile is filling up with code that I'd like to move into a separate file and "require". Specifically I am writing a postcss plugin, which I already have working when declared as a function inside of the gulpfile. My question is how to put my function in an external file and require it like I do a node module. Do I need to "export" the function in the file being required? Do I need to use ES6 modules or something like that?

另外,我意识到如果我这样做,可能(A)将它变成合适的节点模块并将其放置在私有的NPM存储库上,但似乎没有必要,或者(B)将其转换为适当的gulp插件,但这需要学习如何编写一个gulp插件并学习流和内容。这两个都可能会更好,但会花费更多的时间,所以我决定现在保持简单和本地化的功能。

As an aside, I realise that if i was doing this probably I would either (A) turn this into a proper node module and put it on a private NPM repository, but that seems unnecessary, or (B) turn it into a proper gulp plugin, but that would require learning how to author a gulp plugin and learning about streams and stuff. Both of these are probably better but would take more time so I've decided to just keep the function simple and local for now.

推荐答案

首先创建一个新的js文件(这里 ./ lib / myModule.js

First create a new js file (here ./lib/myModule.js):

//./lib/myModule.js
module.exports =  {
    fn1: function() { /**/ },
    fn2: function() { /**/ },
}

您也可以将一些参数传递给您的模块:

You could also pass some arguments to your module:

// ./lib/myAwesomeModule.js
var fn1 = function() {
}
module.exports =  function(args) {
    fn1: fn1,
    fn2: function() { 
        // do something with the args variable
    },
}

然后在你的gulpfile中需要它:

Then require it in your gulpfile:

//gulpfile.js
var myModule = require('./lib/myModule')

// Note: here you required and call the function with some parameters
var myAwesomeModule = require('./lib/myAwesomeModule')({
    super: "duper",
    env: "development"
});

// you could also have done
/*
var myAwesomeModuleRequire = require('./lib/myAwesomeModule')
var myAwesomeModule = myAwesomeModuleRequire({
    super: "duper",
    env: "development"
});
*/

gulp.task('test', function() {
   gulp.src()
    .pipe(myModule.fn1)
    .pipe(myAwesomeModule.fn1)
    .gulp.dest()
}

这篇关于需要gulpfile中的另一个文件(不在node_modules中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆