unplugin-sri

A universal plugin for adding Subresource Integrity (SRI) attributes to your HTML files.
Features
- đź”’ Automatically adds integrity attributes to script and link tags
- 🔄 Supports various hash algorithms (default: sha384)
- 🖼️ Optional support for image files
- 🛠️ Works with Vite, Webpack, Rollup, and more
- 🔍 Supports remote resources (URLs starting with
http or //)
Installation
pnpm install unplugin-sri
Usage
Vite
import SRI from 'unplugin-sri/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
SRI({
}),
],
})
Webpack
module.exports = {
plugins: [
require('unplugin-sri/webpack')({
}),
],
}
Rollup
import SRI from 'unplugin-sri/rollup'
export default {
plugins: [
SRI({
}),
],
}
esbuild
import { build } from 'esbuild'
import SRI from 'unplugin-sri/esbuild'
build({
plugins: [
SRI({
}),
],
})
Nuxt
export default {
buildModules: [
['unplugin-sri/nuxt', {
}],
],
}
Vue CLI
module.exports = {
configureWebpack: {
plugins: [
require('unplugin-sri/webpack')({
}),
],
},
}
Options
interface Options {
algorithm?: string
extensions?: string[]
includeImages?: boolean
onComplete?: () => void
}
How It Works
The plugin works by:
- Waiting for the build process to complete
- Finding all HTML files in the output directory (defaults to
dist)
- Processing each HTML file to:
- Find all
<script> and <link> tags that reference local resources
- Calculate the SRI hash for each referenced file
- Add
integrity and crossorigin="anonymous" attributes to the tags
- Writing the modified HTML files back to disk
Features
- Automatically adds SRI attributes to JavaScript and CSS resources
- Optionally processes image files
- Skips external resources (URLs starting with
http)
- Skips resources that already have an
integrity attribute
- Adds
crossorigin="anonymous" attribute when needed
- Works with all major bundlers through the unplugin interface
Example
Before:
<link href="styles.css" rel="stylesheet">
<script src="main.js"></script>
After:
<link href="styles.css" rel="stylesheet" integrity="sha384-1234abcd..." crossorigin="anonymous">
<script src="main.js" integrity="sha384-5678efgh..." crossorigin="anonymous"></script>
License
MIT