posthtml-hash
posthtml-hash
is a PostHTML plugin for hashing file names to enable caching.
<html> <head>- <link rel="stylesheet" href="styles.[hash].css" />+ <link rel="stylesheet" href="styles.9a6cf95c41e87b9dc102.css" /> </head> <body>- <script src="src.[hash].js"></script>+ <script src="src.b0dcc67ffc1fd562f212.js"></script> </body></html>
Install
yarn add -D posthtml-hash# OR npm i -D posthtml-hash
Usage
Input
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.
<!-- ✅ hashed --> <!-- ❌ not hashed --> <!-- ✅ hashed --> <!-- ❌ not hashed -->
Node.js
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.
// postbuild.jsconst fs = ;const posthtml = ;const hash = ; const html = fs; ;
For convenience, you can add the post-build script to your package.json. The postbuild
script is automatically invoked following the build
script.
Custom Hash Length
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.
<!-- src.b0dcc67ffc1fd562f212.js --> <!-- src.b0dcc67f.js -->
Options
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
:
;
Recipes
Custom Pattern and Hash Length
;
Result:
- <script src="script.custom-file-pattern.js"></script>+ <script src="script.b0dcc67f.js"></script>
Remote origin URLs
Input HTML:
<!-- We want to hash this image file name and preserve the remote origin URL -->
;
Examples
See the examples folder for end-to-end use cases.
Contributing
See the PostHTML Guidelines.