Asset Hash is a quick wrapper around hashing libraries for efficient and fast hashing of asset files like images, web fonts, etc. By default it uses the performance-optimized Metrohash and a Base52 encoding (
[a-zA-Z]) which works well for file names and urls and has a larger dictionary than when using hex.
Table of Contents
$ npm install asset-hash
$ yarn add asset-hash
For speed comparisons of different algorithms we created a small repository containing the source code and some results. Check it out. TLDR: Modern non-cryptographic hashing could be way faster than cryptographic solutions like MD5 or SHA1. Best algorithm right now for our use cases seems to be MetroHash128. This is why we made it the default.
There are two main methods:
getHash(filePath, options) and
getHashedName(filePath, options) and a more traditional class
Hasher(options). Both methods return a Promise with there actual hash or hash file name as a result. The class offers the pretty traditional methods
digest(options) to send data or to retrieve the hash.
hash: Any valid hashing algorithm e.g.
encoding: Any valid encoding for built-in digests
maxLength: Maximum length of returned digest. Keep in mind that this increases collison probability.
The hashed file name replaces the name part of the file with the hash while keeping the file extension.
const hasher =hasherconsole "Hashed Data: XDOPW"
Webpack Example Config
You can use the powerful hashing of AssetHash inside Webpack as well. This leads to a) better performance and b) shorter hashes. Here is an example configuration:
...output:hashFunction: HasherhashDigest: "base52"hashDigestLength: 8...
For more details please check the official Webpack docs.
Sebastian Software GmbH