rewriting/reving relative paths in concatenated css files within gulp-usemin

812 Views Asked by At

I have these requirements:

  1. Concatenate css files.
  2. Rev the concatenated css file.
  3. Rev resource files referenced by css files (images, fonts, etc...). File references are relative and come from third parties, so I have no control over them.
  4. Rewrite file references in css files for revving, and to make them relative to the concatenated file, rather than the original file.

My project layout:

  dist/
    index.html
    app-<hash>.css
    bower_components/
      bootstrap/
        fonts/
          glyphicons-halflings-regular-<hash>.woff
          glyphicons-halflings-regular-<hash>.ttf
          etc...
  app/
    index.html
    appStyles.css
    bower_components/
      bootstrap/
          dist/
              css/
                bootstrap.css
                etc...
          fonts/
              glyphicons-halflings-regular.woff
              glyphicons-halflings-regular.ttf
              etc...

So, as an example, bootstrap.css references glyphicons-halflings-regular.ttf using the relative path: '../../fonts/glyphicons-halflings-regular.ttf'. This needs to be rewritten to the relative path 'bower_components/bootstrap/fonts/glyphicons-halflings-regular-hash.ttf'.

I have been able to get a gulp-usemin task working that concatenates my css files and revs the output. It even works with source maps, which is a bonus (not required).

However, I can't get usemin to rewrite paths in css files to adjust for revving and to make them relative to the concatenated file. How do I do this? Do I need another plugin in the css chain? Here is what I have so far:

var resourcesRevved = [
    'app/bower_components/bootstrap/**/*.ttf',
    'app/bower_components/bootstrap/**/*.woff',
    etc...
];

gulp.task('copy:resources:revved', ['clean:dist'], function() {
    return gulp.src(resourcesRevved)
        .pipe(rev())
        .pipe(gulp.dest('dist'));
});

gulp.task('usemin', ['copy:resources:revved'], function() {
    return gulp.src('./app/index.html')
        .pipe(usemin({
            css: [
                sourcemaps.init({
                    loadMaps: true
                }),
                'concat',
                rev(),
                sourcemaps.write('.')
            ]
        }))
        .pipe(gulp.dest('dist/'));
    });

Here is the usemin section in index.html:

<!-- build.css app.css -->
<link href="bower_components/bootstrap/dist/css/bootstrap.css" rel="stylesheet">
<link href="app/appStyles.css">
etc...
<!-- endbuild -->
0

There are 0 best solutions below