0

我配置了以下 gulp 任务:

  var assets = plugins.useref.assets({searchPath: './'}),
        css = plugins.filter('**/main.css'),
        html = plugins.filter('**/*.html');
    return gulp
        .src(config.html.srcheader)
        .pipe(plugins.plumber())
        // collect all assets from source file by the means of useref
        .pipe(assets)
        //// minify main.css
        .pipe(css)
        .pipe(plugins.csso())
        .pipe(css.restore())
        //// Take inventory of the file names for future rev numbers
        .pipe(plugins.rev())
        //// Apply the concat and file replacement with useref
        .pipe(gulp.dest(config.rootdir))
        .pipe(assets.restore())
        .pipe(plugins.useref())
        //// Replace the file names in the html with rev numbers
        .pipe(plugins.revReplace())
        .pipe(transformStream())
        //// rename source
        .pipe(html)
        .pipe(plugins.rename(config.html.customer.targetheader))
        .pipe(gulp.dest(config.html.dir));

该代码采用 css 文件,缩小它们,添加修订版(例如 main-abcde123.css),用处理后的文件替换源文件的出现。这是通过 gulp-useref/gulp-rev/gulp-rev-replace plugins 完成的(plugins是一个具有所有已加载插件的对象,即 plugins.useref - 指 gulp-useref 插件)此代码工作正常。我正在尝试对同一流中的结果 css 文件进行一些修改。这是通过transformStream()如下所示的函数完成的:

function transformStream() {

    var collect = function(file, enc, cb) {

        console.log(file);
        return cb();
    }

    var emit = function(cb) {
        return cb();
    }

    return through.obj(collect, emit);
}

在这种情况下throughgulp-through2插件。

请看下面的代码console.log(file);。我正在尝试获取缩小的 css 的文件名。上面的代码显示以下内容:

<File "assets/main-34d85b66.css" <Buffer 40 63 68 61 72 73 65 74 20 22 55 54 46 2d 38 22 3b 40 66 6f 6e 74 2d 66 61 63 65 7b 66 6f 6e 74 2d 66 61 6d 69 6c 79 3a 22 6d 74 63 22 3b 73 72 63 3a ... >>

即它不包含文件名,而是某种缓冲区。我阅读了through2文档,但没有澄清这些事情。

所以,我的问题是:我怎样才能访问实际的文件名?

4

2 回答 2

0

你试过gulp-filenames吗?我不确定它在这种情况下如何工作,但它会将新的版本化文件名存储在内存中。像这样的东西:

...
return gulp
    .src(config.html.srcheader)
    .pipe(plugins.plumber())
    .pipe(assets)
    .pipe(css)
    .pipe(plugins.csso())
    .pipe(css.restore())
    .pipe(plugins.rev())
    .pipe(gulp.dest(config.rootdir))
    .pipe(assets.restore())
    .pipe(plugins.useref())
    .pipe(plugins.revReplace())
    .pipe(plugins.fileNames('my-css-file'))
 }

然后你可以稍后获取文件名

function transformStream() {
    var fileName = plugins.fileNames.get('my-css-file')
}
于 2016-04-20T23:04:17.813 回答
0

您可以通过对其进行一些简单的迭代来从文件中获取属性:

for (var property in file) {
  console.log(property);
}

/*
  history               
  cwd                   
  base                  
  stat                  
  _contents             
  isBuffer              
  isStream              
  isNull                
  isDirectory           
  clone                 
  pipe                  
  inspect  
*/

如果您只是在寻找文件名,那么 file.relative 就是您所需要的。

  • file.history 会给你工作目录+文件名
  • 当前工作目录的 file.cwd
  • 基本路径的 file.base
  • 等等
于 2016-04-20T20:30:03.933 回答