Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does gulp-useref does not seem to work with a comment in the replacement section?

I am trying to build a gulp pipeline – I want to inject some CSS into my index.html (this works fine) and then grab all the other links from source index.html and replace them in the outputted version.

I noticed that the useref call is mangling the output if the templated section to replace includes an HTML comment (see example below for the line COMMENT). It’s easiest to demonstrate with code:

index.html (source file)

<!-- build:css styles/app.css-->
<!--COMMENT-->
<link rel="stylesheet" href="/.tmp/styles.css">
<!-- endbuild -->

gulpfile.js task

gulp.task('optimizeReplace', function () {
    var assets = $.useref.assets({ searchPath: './' });

    return gulp
        .src('./src/client/index.html')
        .pipe(assets)
        .pipe(assets.restore())
        .pipe($.useref())  //THIS IS THE PROBLEM LINE; IF INJECT IS NOT RUN FIRST IT IS MANGLED
        .pipe(gulp.dest('./wwwroot/'));
});

Output (index.html)

</style>
<link rel="stylesheet" href="styles/lib.css">
<link rel="stylesheet" href="styles/app.css-->" <!--COMMENT>
</head>

<body>
  <div>

The problem is easier to see in HTML, but the COMMENT HTML comment looses the end half of its tag, so everything after it thinks it is a comment.

The reason I want to put a comment inside the replacement section is that the comment is actually a gulp-inject statement which injects some other references before I do the useref. I simplified it down to a simple HTML comment causing the problem.

This is the line that causes the problem: .pipe($.useref())

FYI I am following John Papa’s course on Pluralsight where he uses this exact mechanism to inject some CSS and then replace them – (the inject:css HTML comment delimiters are mangled after a useref):

<!-- build:css styles/app.css-->
<!-- inject:css -->
<link rel="stylesheet" href="/.tmp/styles.css">
<!-- endinject -->
<!-- endbuild -->

How can I get the useref() to replace the template with the correct links but leave the HTML comment intact?

Thanks.

like image 836
Rodney Avatar asked Apr 29 '15 13:04

Rodney


1 Answers

The reason is version change check documentation https://www.npmjs.com/package/gulp-useref here you have an example:

gulp.task('optimize', ['templateCache', 'images'], function(){

    var templateCache = config.temp + config.templateCache.files;

    return gulp
    .src(config.index)
    .pipe($.plumber())
    .pipe($.inject(gulp.src(templateCache, {read: false}, {starttag: ''})))
    .pipe($.useref({ searchPath: './' }))
    .pipe(gulp.dest(config.build));
});

hope it helps

like image 172
Pedro Lescano Avatar answered Oct 23 '22 01:10

Pedro Lescano