vitaly63
vitaly63

Reputation: 35

Grunt, replacing path to image in css

When you compile the project Grunt need to pass in the compiled css files, replace all the way up to the desired image.

We need this in order to have outside package has its own folder with images, such as dist/images/vendor.

The file in which you want to search, is compiled from a outside styles set through the bower. Accordingly, each plug-in style their way to images, this decision was made to load all the images in a folder and the way to rewrite them to suit.

We have:

  1. Compiled style is dist/css/bundle-vendor.css.
  2. fancybox style is vendor/fancybox/source/jquery.fancybox.css.
  3. fancybox copied image is dist/images/vendor.

As a result of this:

#fancybox-loading, .fancybox-close, .fancybox-prev span, .fancybox-next span {
    background-image: url('fancybox_sprite.png');
}

get the form:

#fancybox-loading, .fancybox-close, .fancybox-prev span, .fancybox-next span {
    background-image: url('../images/vendor/fancybox_sprite.png');
}

I would like to know whether there is a solution that preserves the path from the root, into the desired folder. And in this case, we get the following:

#fancybox-loading, .fancybox-close, .fancybox-prev span, .fancybox-next span {
    background-image: url('../images/vendor/fancybox/source/fancybox_sprite.png');
}

Upvotes: 0

Views: 553

Answers (1)

vitaly63
vitaly63

Reputation: 35

npm install grunt-string-replace --save

Grunt.js

grunt.loadNpmTasks('grunt-string-replace');

Add Task

string-replace

grunt.initConfig add

'string-replace': {
        inline: {
            src: [
                'dist/css/<%= that.name %>-vendor.css'
            ],
            dest: "dist/css/<%= that.name %>-vendor-rep.css",
            options: {
                replacements: [{
                    pattern:  /:(\s*)(url\(\s*[\"\']*)(?:[^\"\']+\/)?([^\/\"\'\)]+[\"\']*\s*\))/ig,
                    replacement: ': $2../images/vendor/$3'
                }]
            }
        }
    }

Thx @Visman

Upvotes: 1

Related Questions