node.js - 在 Gulp 3.9.1 中的管道之间传递变量

标签 node.js gulp pipe uuid gulp-print

使用 gulp 3.9.1

我正在尝试返回一堆文件并执行一项需要在两个管道之间传递 var 的任务。

  1. 我正在使用 Node uuid 为每个文件路径创建一个 v3 UUID 最终每个页面都会有一个 uuid。我正在使用 gulp-print 获取文件路径。
  2. 我想将该 uuid 值存储为 var。在下一个管道中我使用 gulp-inject-string 在构建期间将其写入页面。

帮助:要么我需要帮助获取 gulp-inject-string 管道内的文件路径,要么我需要在两个不同的管道之间传递 var。如果我在 src 之外全局设置一个具有默认值的 var,它会很容易地传递到管道(注入(inject))。

下面的 super 简化代码:

// test code
var gulp = require('gulp');
var print = require('gulp-print');
var inject = require('gulp-inject-string');
var reload = browserSync.reload;

const uuidv3 = require('uuid/v3');
var uuid;

gulp.task('uuid', function() {

    return gulp.src('**/*.html'])

        // create uuid
        .pipe(print(function(filepath) {
            uuid = uuidv3(filepath, uuidv3.URL);
            return "compiled: " + filepath + ' uuid: ' + uuid;
        }))

        // need to to add UUIDv3 to each page
        .pipe(inject.before('</head>', '<meta name="dc.identifier" content="' + uuid + '">'))
        .pipe(gulp.dest('/prod/./'))

        .pipe(reload({ stream: true }));
});

值得注意的是,我需要一种跨平台的方式来获取从项目根目录开始并包含正斜杠的文件路径。 gulp(print) 从项目的根部开始完美地执行此操作,并忽略该点上游的任何内容。路径的格式很重要,因为它是创建 uuid 等式的一半,并且 uuid 必须在 Mac 或 PC 平台上匹配。

示例:

/index.html  
/dir1/file.html  
/dir1/dir2/dir3/file.html

最佳答案

var gulp            = require('gulp');
var print           = require('gulp-print');
var inject          = require('gulp-inject-string');
const uuidv3        = require('uuid/v3');

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

// you can declare here
var uuid;

gulp.task('pages', function() {

    // or you can declare here
    var uuid;

return gulp.src('**/*.html')
    // bunch of stuff happens here involving templating/minifying
    // create uuid
    .pipe(print(function(filepath) { 

        // then set it here and use it further below
        // it will be available

        uuid = uuidv3(filepath, uuidv3.URL);

        return "compiled: " + filepath + ' uuid: ' + uuid;
    }))
    // need to to add UUIDv3 to each page
    //.pipe(inject.before('</head>', '<meta name="dc.identifier" content="' + uuid + '">\n'))

  .pipe(tap(function(file, t) {

    return t.through(inject.before('</head>', '<meta name="dc.identifier" content="' + uuid + '">\n');

   })

    .pipe(gulp.dest('/prod/./')) 
    .pipe(reload({stream:true}));    
});

您只是在更高的范围内创建一个变量,您可以在以后设置和引用该变量。如果您需要一堆文件,请创建一个以文件路径作为索引的数组。但我会首先尝试它只是一个简单的值。

关于node.js - 在 Gulp 3.9.1 中的管道之间传递变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48506157/

相关文章:

gitignore - 忽略文件夹中生成的文件,但不忽略文件夹

macos - 如何 cd 到脚本回显的目录

bash - 在命令之间转义管道输出

c - `echo "asdf "` 到使用管道的 C 程序

node.js - 在 Nuxt JS 中设置 Cache-Control header 适用于本地主机但不适用于生产

mysql - 表达 mysql session

node.js - 适用于 NodeJs 的 Azure 通知中心(注册更新并替换标签)

node.js - 如何使用 node.js 解码并验证 AWS SigV4 请求的签名

javascript - gulp-usemin 不输出 js 文件

angularjs - 在 Controller 中找不到 fs