Adds Subresource Integrity (SRI) hashes to HTML files.
It does so, by parsing the contents of passed in HTML files with cheerio, looking for
<link rel=stylesheet href=URL> and
<script src=URL> DOM-nodes, computing checksums for found referenced files, and adding
integrity=<HASH> attributes in-place to respective DOM-nodes.
Inspiration for this plugin came from working with static site generators.
For an alternative approach, have a look at the gulp-sri plugin.
Install package with NPM and add it to your development dependencies:
npm install gulp-sri-hash --save-dev
const sriHash = ;gulp;
This will look for css and js file references contained in all html-files, calculate SRI-hashes for those files, and add
integrity=<HASH> attributes for those references.
Referenced css- and js-files must be accessible from the local filesystem. In order to calculate correct hashes, style and script files should not be modified any further by build steps running later.
Content hashing is sensitive to differences in line-endings. On Windows, the default is
CRLF, whereas (all?) other Operating Systems default to
You're good, as long the files use the same end-of-line sequence locally as well as on the server that delivers those asset files.
On the other hand, a change of line-endings after content hashing will cause a file checksum mismatch.
- Since: v1.0.0
Select hashing algorithm. Supported algorithms:
- Since: v1.1.0
Strips string from beginning of referenced URI in HTML files. Useful if references do not match directory structure or already contain CDN hostname.
- Since: v1.1.0
Only look for nodes matching this custom (jQuery-style) selector.
- Since: v1.2.0
Controls whether referenced files should be resolved relative to a base folder, or relative to the location of the HTML file.
Inspired by https://github.com/macedigital/gulp-sri-hash/pull/1.
Following snippet shows all options in action:
// ...// ...
Require a peer-dependency of gulp 4.x and drop support for nodejs 4.x which reached its End-of-Life on April 30th 2018.
Querystring-like components in file paths are ignored when resolving local files. As an example, the given string
/folder/style.css?v=somehash will resolve to local file
crossorigin=anonymous attribute will be added to all updated DOM nodes, unless the attribute has been already been set to value
use-credentials. In the latter case the
crossorigin attribute is left unchanged.