posthtml-hash
is a PostHTML plugin for hashing static assets. This plugin uses hasha to generate unique hashes.
Currently, this plugin supports CSS and JS files.
Before:
<html>
<head>
<link rel="stylesheet" href="stylesheet.css" />
</head>
<body>
<script src="main.js"></script>
</body>
</html>
After:
<html>
<head>
<link rel="stylesheet" href="stylesheet.9a6cf95c41e87b9dc102.css" />
</head>
<body>
<script src="main.b0dcc67ffc1fd562f212.js"></script>
</body>
</html>
yarn add -D posthtml-hash
# OR
npm i posthtml-hash
const fs = require('fs');
const posthtml = require('posthtml');
const { hash } = require('posthtml-hash');
const html = fs.readFileSync('./index.html');
posthtml()
.use(hash())
.process(html)
.then(result => fs.writeFileSync('./index.html', result.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
:
const fs = require('fs');
const posthtml = require('posthtml');
const { hash } = require('posthtml-hash');
const html = fs.readFileSync('./public/index.html');
posthtml()
.use(
hash({
/**
* Relative path to processed HTML file
*/
path: 'public',
/**
* Length of hash
* Default is 20
*/
hashLength: 10
})
)
.process(html)
.then(result => fs.writeFileSync('./index.html', result.html));
See the PostHTML Guidelines.