用gulp生成文件

rob*_*rob 6 javascript build-process node.js gulp

我有一个项目,setup.js在我的/src文件夹中的各个子文件夹中调用了几个文件.我想要一个gulp任务将所有setup.js文件复制到一个/dist文件夹并保留子文件夹结构.这部分很容易.

棘手的部分是我还想在setup.js文件\dist夹中的每个文件旁边生成一个index.html文件.index.html文件对于所有这些文件将完全相同,只是它需要setup.js使用相对于/dist文件夹的路径来引用脚本.我知道我可以使用一些像gulp-template来动态渲染一个html文件,但我不知道如何将路径传递给setup.js它.我不知道如何index.html为每个人创造一个setup.js.

所以我想要的结果文件夹结构看起来像这样

/src
    template.html
    /blah1
        setup.js
    /blah2
        setup.js
/dist
    /blah1
        setup.js
        index.html
    /blah2
        setup.js
        index.html
Run Code Online (Sandbox Code Playgroud)

我对如何做到这一点有任何想法吗?

或者,如果有人可以将我链接到一些关于Gulp的详细文档/示例/教程,这些文档/示例/教程可能会解释如何进行类似这样的事情,我将非常感激.我没有找到很多好的文章,它们实际上解释了Gulp幕后发生的事情,而且很难找到超越琐碎src | uglify | concat | dest用例的例子.

谢谢!

brb*_*ing 7

我当然不是gulp或节点的专家,所以随时纠正我/添加到我的答案...

我试图将类似的目录结构复制到你在这里描述的内容......

使用gulp-tap和gulp-template

gulpfile.js

var gulp = require('gulp');
var template = require('gulp-template');
var tap = require('gulp-tap');

gulp.task('default', function () {
  gulp.src('./src/**/**.js', { base: './src' })
    // tap into the stream to get the current file and compile
    // the template according to that
    .pipe(tap(function (file) {
      gulp.src('./src/template.html')
        // compile the template using the current
        // file.path as the src attr in the template file
        .pipe(template({
          sourcefile: file.path
        }))
        // not sure about this line but I'm sure it could be better
        // splits the path on the / and then uses the second to last
        // item in the split array (which is the current directory, minus src plus dist)
        .pipe(gulp.dest('./dist/' + file.path.split('/')[file.path.split('/').length - 2]))
    }))
    // finally put the javascript files where they belong
    .pipe(gulp.dest('./dist'))
});
Run Code Online (Sandbox Code Playgroud)

template.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <script src="<%- sourcefile %>"></script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

开始目录结构

.
|____dist
|____gulpfile.js
|____src
| |____bar
| | |____setup.js
| |____foo
| | |____setup.js
| |____template.html
Run Code Online (Sandbox Code Playgroud)

最终目录结构

.
|____dist
| |____bar
| | |____setup.js
| | |____template.html
| |____foo
| | |____setup.js
| | |____template.html
|____gulpfile.js
|____src
| |____bar
| | |____setup.js
| |____foo
| | |____setup.js
| |____template.html
Run Code Online (Sandbox Code Playgroud)