jonkemp / gulp-useref

Parse build blocks in HTML files to replace references to non-optimized scripts or stylesheets.
MIT License
705 stars 93 forks source link

Does not work with gulp-autoprefixer and gulp-sourcemaps #159

Open medifle opened 8 years ago

medifle commented 8 years ago

OS X El Capitan@10.11.1 node@4.2.3 gulp-useref@3.0.0 (For versions info, see this package.json)

TL;DR

I am considering managing all my assets through HTML build blocks. gulp-useref is ideal, taking assets in HTML as a stream that can be piped to other plugins rather than use gulp.src() to define assets path, especially for multiple HTML files.

Here is the major issue I struggled with. See '@ THE ISSUE' in code below:

├── app
│   ├── index.html
│   ├── scripts
│   │   └── main.js
│   └── styles
│       ├── main.scss
│       └── src
├── gulpfile.babel.js
└── package.json
gulp.task('html', () => {
  return gulp.src('app/index.html')

  .pipe($.useref({},

    // after assets in HTML is searched out,
    // transform them before concat
    lazypipe()
    .pipe($.sourcemaps.init)
    .pipe(function() {
      return $.if(/\.scss$/, $.sass({
        precision: 10
      }).on('error', $.sass.logError));
    })

    //# @THE ISSUE
    //# it seems gulp-autoprefixer changed the value of "sources" entry in main.css.map,
    //# which in turn cannot be identified by Chrome.
    .pipe(function() {
      return $.if(/\.css$/, $.autoprefixer());
    })
  ))

  .pipe($.if(/\.css$/, $.sourcemaps.write('.')))

  .pipe($.size({
      title: 'html',
      showFiles: true
    }))
    .pipe(gulp.dest('dist'))
});

I've tested some cases:

Conclusion: gulp-useref seems cannot co-exist with gulp-autoprefixer and gulp-sourcemaps.

Does the stream that gulp-useref emits differ from the one that gulp.src() does?

Details

Here is a reduced test case with a test HTML file, a gulpfile.babel.js and a package.json included. Feel free to clone and try.

The Purpose

To manage all assets, generally including Scss, JS, CSS(from bower), through HTML build blocks. The workflow would be simple and effective, especially for the scenario we have multiple HTML files including different assets. So we do not need to change assets path manually in gulpfile.js for another HTML file including assets different from previous ones.

To manage 'Scss' files directly from HTML, this might be the ideal workflow:

  1. put the relative 'Scss' path in HTML, like this

     <!-- build:css styles/main.css -->
     <link rel="stylesheet" href="styles/main.scss">
     <!-- endbuild -->
  2. allow gulp-useref to analyze 'Scss' assets to be transformed, and use
  3. gulp-sass to compile 'Scss' files
  4. gulp-autoprefixer to process the vendor prefixes of CSS files
  5. gulp-sourcemaps to generate sourmaps.

However the sourcemaps issue is probably at Step 2, 4 or 5.

For now, I use a workaround that yeoman does: