sindresorhus / gulp-rev

Static asset revisioning by appending content hash to filenames: `unicorn.css` → `unicorn-d41d8cd98f.css`
MIT License
1.54k stars 217 forks source link

Change JSON key #229

Closed beefchimi closed 7 years ago

beefchimi commented 7 years ago

I'm using this plugin to feed a service-worker manifest, where the asset file names never actually change, but I can request an update if the hash ends up being different.

Struggling to figure out how I can control the keys of my manifest. Basically, what I get by default will be:

"file.js": "file-asdasdw.js"

when what I really want is:

"/assets/js/file.js": "asdasdw"

Now, I have successfully figured out how to get just the revHash as the value by doing this:

import gulp from 'gulp';
import rev from 'gulp-rev';
import through from 'through2';
import cacheManifest from '../cache-manifest';

function extractHash(file, enc, cb) {
  file.path = file.revHash;
  cb(null, file);
}

export function revision() {
  return gulp.src(cacheManifest)
    .pipe(rev())
    .pipe(through.obj(extractHash))
    .pipe(rev.manifest('./assets-manifest.json'))
    .pipe(gulp.dest('./'));
}

But I'm struggling with the key. For now, I've had to edit this section of the source code to be:

const trimmedPath = file.revOrigBase.replace(/^(.*?)\/dist/, '')
const revisionedFile = relPath(file.base, file.path);
const originalFile = path.join(path.dirname(revisionedFile), path.basename(file.revOrigPath)).replace(/\\/g, '/');
const newPath = trimmedPath + originalFile;

manifest[newPath] = file.revHash;

Working for now but I'd prefer not to be altering my dependencies :)

Any help would be greatly appreciated! Thanks!

bobthecow commented 7 years ago

Don't use rev.manifest at all. Just write the manifest directly instead of your extractHash stuff :)

beefchimi commented 7 years ago

Solved it by just using the rev-hash dep directly:

import fs from 'fs';
import revHash from 'rev-hash';
import cacheManifest from '../../src/scripts/cache-manifest';

const assetsManifestPath = './assets-manifest.json';

export function revision() {
  return new Promise((resolve) => {
    const obj = {};

    cacheManifest.forEach((item) => {
      const key = item.replace('dist', '');
      obj[key] = revHash(fs.readFileSync(item));
    });

    resolve(obj);
  }).then((manifest) => {
    return fs.writeFileSync(assetsManifestPath, JSON.stringify(manifest, null, 2), 'utf-8');
  }).catch((error) => {
    return console.log(error); // eslint-disable-line no-console
  });
}