gulpgulp-rev

How to replace Filenames inside my manifest.json File using rev-replace


i'm stuck a little - i want to replace image file names with their hashed version inside my manifest file.

Manifest looks like this:

{
"icons": [
    {
        "src": "android-chrome-192x192.png",
        "sizes": "192x192",
        "type": "image/png"
    },
    {
        "src": "android-chrome-512x512.png",
        "sizes": "512x512",
        "type": "image/png"
    }
]
}

I want those icon src to be replaced with the hashed filenames which looks like this: "android-chrome-192x192-b03df0131.png"

My gulp file which should do it looks like this:

    const gutil = require('gulp-util');

module.exports = function (gulp, plugins) {
    return function () {
        const manifest = gulp.src('public/dist/rev-manifest.json');

        return gulp.src(['public/dist/@(css|js)/**','public/dist/img/icon/**.json'])
            .pipe(plugins.revReplace({replaceInExtentions: ['.json']}))
            .pipe(plugins.revReplace({manifest: manifest}))
            .pipe(gulp.dest('public/dist'));
    };
};

Solution

  • after a lot of googling and Documentation reading i got it working :D

    So if someone searches for this:

    const gutil = require('gulp-util');
    
    module.exports = function (gulp, plugins) {
        return function () {
            const manifest = gulp.src('public/dist/rev-manifest.json');
    
            function replaceIconPath(filename) {
                if(filename.includes('android-chrome-')) {
                    return filename.replace('img/icon/', '');
                }
    
                return filename;
            }
    
            return gulp.src('public/dist/@(css|js|img)/**')
                .pipe(plugins.revReplace({
                    replaceInExtensions: ['.json', '.css', '.js', '.html', '.hbs'],
                    manifest: manifest,
                    modifyUnreved: replaceIconPath,
                    modifyReved: replaceIconPath
                }))
                .pipe(gulp.dest('public/dist'));
        };
    };
    

    So let me explain this shortly - the important part is in plugins.revReplace.

    You need the option replaceInExtension and add '.json' but you also need to specify the default options or else they will be lost.

    The 'modifiyUnreved' and 'modifyReved' options are just needed if you have to modify the filenames further. In my case it couldn't find the file because my rev-manifest was on another level compared to my manifest file. So i needed to cut the path for it to find the src and replace it.