Search code examples
gulpgulp-useref

Strange behavior of Gulp Useref after HTML injection


Putting, in src/ directory, a main page (index.html) like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- build:css styles/index.css -->
    <link rel="stylesheet" href="styles/index.css">
    <!-- endbuild -->
</head>
<body></body>
</html>

And a CSS file (index.css in styles/ dir.) like e.g.:

body {
    background-color: red;
}

I configure a Gulp task that link the CSS file with the HTML one:

const gulp = require('gulp'),
    injStr = require('gulp-inject-string'),
    useref = require('gulp-useref');

gulp.task('default', () => {
    const tab = '    ',
        nl = '\n',
        nlTab = nl + tab;
    return gulp.src('src/index.html')
        //.pipe(injStr.before('</head>', tab + '<!-- build:css styles/index.css -->' + nlTab + '<link rel="stylesheet" href="styles/index.css">' + nlTab + '<!-- endbuild -->' + nl))
        .pipe(useref())
        .pipe(gulp.dest('.tmp/'));
});

If Gulp is executed, all the comments content is transformed to <link rel="stylesheet" href="styles/index.css">. Ok, it is normal.

Well, the problem occurs when I want simplify it avoiding write the comments manually in HTML. Uncomment the JS sourcecode (line 10), delete comments in HTML (8-10) and execute again. Gulp Useref does nothing! Transformation is not working. Why!?


Solution

  • I discovered the solution!:

    The carriage return character is missing. Use '\r\n' instead of the lonely '\n'.