unplugin-sri
v0.0.11
Published
[](https://www.npmjs.com/package/unplugin-sri)
Downloads
17
Maintainers
Readme
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
httpor//)
Installation
pnpm install unplugin-sriUsage
import SRI from 'unplugin-sri/vite'
// vite.config.js
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
SRI({
// options
}),
],
})// webpack.config.js
module.exports = {
plugins: [
require('unplugin-sri/webpack')({
// options
}),
],
}// rollup.config.js
import SRI from 'unplugin-sri/rollup'
export default {
plugins: [
SRI({
// options
}),
],
}// esbuild.config.js
import { build } from 'esbuild'
import SRI from 'unplugin-sri/esbuild'
build({
plugins: [
SRI({
// options
}),
],
})// nuxt.config.js
export default {
buildModules: [
['unplugin-sri/nuxt', {
// options
}],
],
}// vue.config.js
module.exports = {
configureWebpack: {
plugins: [
require('unplugin-sri/webpack')({
// options
}),
],
},
}Options
interface Options {
/**
* Hash algorithm to use for SRI
* @default 'sha384'
*/
algorithm?: string
/**
* File extensions to process
* @default ['.js', '.css']
*/
extensions?: string[]
/**
* Whether to include image files
* @default false
*/
includeImages?: boolean
/**
* Callback function to execute when processing is complete
*/
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
integrityandcrossorigin="anonymous"attributes to the tags
- Find all
- 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
integrityattribute - 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>