The Problem
To enable the sub-resource integrity feature, a cryptographic hash string of the resource file is required. For static files or resources hosted by a CDN, this hash string would also be static and is often provided. However, for resources generated at build time, we will need to calculate the hash string for each build.
For Vite, it does not come with the capability to generate this hash. Fortunately, several open source plugins close this gap.
The Fix
1) We picked the vite-plugin-manifest-sri plugin. Add it into the package.js
"devDependencies": {
// etc
"vite": "^7.0",
"vite-plugin-manifest-sri": "^0.2.0"
}
2) Install the package
npm install
3) Update vite.config.js
export default defineConfig({
plugins: [
// etc etc
manifestSRI(),
],
});
4) Run the build and check the result
npm run build
The result
1) In the build output (e.g., public directory), look for a file named manifest.json and observe that the integrity hash string is now available.
2) Render the HTML page, and you should see:
<script src="app-........js" integrity="sha384-QQnj/R0s......">
Configuration
1) SHA512 algorithm is also supported.
manifestSRI({
algorithms: [ 'sha512' ]
}),