使用 gulp 3.9.1
我正在尝试返回一堆文件并执行一项需要在两个管道之间传递 var 的任务。
- 我正在使用 Node uuid 为每个文件路径创建一个 v3 UUID 最终每个页面都会有一个 uuid。我正在使用 gulp-print 获取文件路径。
- 我想将该 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/