2

I am using gulp useref to replace/concat my files in my index.html after I minify them. I can get useref to work when I pass a path, but I would like to have it keep the file's original path when I don't define a path. I know I could go through and add the build path comment to each file or that I could just run a task to minify all other files. That just seems crazy and pointless if useref can output the original path then this task to would do it all.

Example - to note stripped code for example aka rel="".

HTML file:

<!-- build:css I want this to return original path into my new "dist" folder. -->
    <link href="fonts/map/map.css">
    <link href="layout/item/item.css">
<!-- endbuild -->

this works bc path is defined and the files exist in the same folder.
<!-- build:css styles/combined.css -->
    <link href="styles/style.css">
    <link href="styles/color.css">
<!-- endbuild -->

Gulp Task:

gulp.task('css', function () {
        return gulp.src('index.html')
            .pipe(useref())
            .pipe(minifyCss())
            .pipe(gulp.dest('dist'));
    });

Resulting HTML - the index.html file is outputed to the "dist" folder and the .css files are minified. This all works, but noticed the href = "replace" bc nothing was defiened in the comments for path, also a file named undefined is outputed in the dist folder:

<link href="replace">
<link href="css/combined.css">

and what I want is...

<link href="fonts/map/map.css">
<link href="layout/item/item.css">
<link href="css/combined.css">
RooksStrife
  • 1,647
  • 3
  • 22
  • 54
  • I might try a different Gulp Plugin - https://www.npmjs.com/package/gulp-inject - I'll try if this post doesn't get anywhere. Seems inject might be a better solution. – RooksStrife Jan 14 '16 at 21:14

1 Answers1

0

I had this same issue. I've found that this is because gulp-useref sets the base property on Vinyl files to be the parent directory of the files. Luckily this can be easily changed with a custom plugin:

// other imports...
const through = require('through2');

function useRefTask() {
    return src('.tmp/**/*.html')
    .pipe(useref())
    .pipe(through.obj((file, _, cb) => {
        file.base = path.join(process.cwd(), "src"); // Change to whatever your input directory is.
        cb(null, file);
    })
    // rest of the pipeline...
}

Note: dest uses the relative property to determine where it'll write files, so it's worth looking at that and making sure it preserves the directory structure.