Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usemin and rewriting urls of images in vendor CSS files using Grunt

grunt-usemin helps me to transform

<link href="/dependencies/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="/dependencies/nanoscroller/bin/css/nanoscroller.css" rel="stylesheet" />
<link href="/dependencies/dropzone/downloads/css/dropzone.css" rel="stylesheet" />

to a perfectly combined and minified js:

<link href="scripts/8e1991c7.libraries.js" rel="stylesheet" />

After concat, cssmin and uglify I have a almost perfect folder structure except for images and their locations.

Here is my problem:

All these vendor's css files are including image locations. The bad thing is that all of them are sharing different kind of locations. Some of them are using images inside css folder whereas others are using inside img folder.

How can I configure grunt usemin to rewrite all images urls?

like image 649
Cemo Avatar asked Oct 31 '13 11:10

Cemo


2 Answers

1) Rev images. Add paths of images into rev task.

rev: {
    dist: {
        files: {
            src: [
                '<%= yeoman.dist %>/static/scripts/{,*/}*.js',
                '<%= yeoman.dist %>/static/styles/{,*/}*.css',
                '<%= yeoman.dist %>/static/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
            ]
        }
    }
}

2) Add paths of file which are including image locations into usemin task.

usemin: {
    html: ['<%= yeoman.dist %>/{,*/}*.html'],
    css: ['<%= yeoman.dist %>/static/styles/{,*/}*.css'],
    options: {
        assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist%>/static/images'],
    }
}

3) Run grunt.

like image 196
Frank Fang Avatar answered Oct 20 '22 02:10

Frank Fang


I've solved the problem using the following.

useminPrepare: {
    html: 'src/index.html',
    options: {
        dest: 'build',
        flow: {
            html: {
                steps: {
                    js: ['concat', 'uglifyjs'],
                    css: ['cssmin']
                },
                post: {}
            }
        }
    }
},
cssmin: {
    options: {
        root: 'src'
    }
}

First, we are overriding useminPrepare's flow, removing the concat task from the css flows. This is needed because concat will destroy relative path information. Since cssmin will itself concat multiple files together, the sepearte concat task is only harmful. (https://github.com/yeoman/grunt-usemin/issues/225)

Lastly, we are telling cssmin where the "root" of your project is from the Gruntfile. This helps cssmin rewrite the relative urls it finds relative to this "root" directory.

like image 38
Justin Avatar answered Oct 20 '22 03:10

Justin