PostHTML plugin for hashing static assets
npm install posthtml-hash[![NPM][npm]][npm-url]
posthtml-hash is a PostHTML plugin for hashing file names to enable caching.
``diff`
-
+
-
+
`bash`
yarn add -D posthtml-hashOR
npm i -D posthtml-hash
By default, the plugin will attempt to hash file names that contain [hash]. As an additional qualifier, only nodes containing href, src, or content attributes are eligible.
`html
`
The recommended usage of this plugin is to incorporate it in your post-build process.
Let's say that you use Rollup to bundle and minify your CSS and JavaScript. The template index.html is copied to the build folder.
`js
// postbuild.js
const fs = require("fs");
const posthtml = require("posthtml");
const { hash } = require("posthtml-hash");
const html = fs.readFileSync("./build/index.html");
posthtml()
.use(hash({ path: "build" }))
.process(html)
.then((result) => fs.writeFileSync("./build/index.html", result.html));
`
For convenience, you can add the post-build script to your package.json. The postbuild script is automatically invoked following the build script.
`json`
{
"scripts": {
"build": "rollup -c",
"postbuild": "node postbuild.js"
}
}
Customize the hash length by specifying an integer after the hash:{NUMBER}. The default hash length is 20.
Note: This only works for a pattern that uses square brackets and a colon separator. Use the hashLength option for different patterns.
`html
`
This plugin assumes that the file to process is in the same directory as the PostHTML script. If not, specify the relative path to the html file in options.path:
`js
hash({
/**
* Relative path to the HTML file being processed
* @default ""
*/
path: "public",
/**
* File name pattern (regular expression) to match
@default new RegExp(/\[hash.]/g)
*/
pattern: new RegExp(/custom-file-pattern/),
/**
* Hash length
* @default 20
*/
hashLength: 8,
/**
* Transform the href/src/content attribute value to a relative file path
* @default (filepath) => filepath
*/
transformPath: (filepath) => filepath.replace("https://example.com/", ""),
});
`
`js`
hash({
pattern: new RegExp(/custom-file-pattern/),
hashLength: 8,
});
Result:
`diff`
-
+
Input HTML:
`html`
`js``
hash({
transformPath: (filepath) => {
// removes the targeted remote origin URL when looking up the files locally
return filepath.replace("https://example.com/", "");
},
});
See the examples folder for end-to-end use cases.
See the PostHTML Guidelines.
[npm]: https://img.shields.io/npm/v/posthtml-hash.svg?color=%23fb7954
[npm-url]: https://npmjs.com/package/posthtml-hash