vite-plugin-inject-sw-assets
Version:
A Vite plugin that injects static assets into a custom service worker for use with injectManifest (ideal for Workbox + vite-plugin-pwa setups).
16 lines (15 loc) • 811 B
JavaScript
/**
* Writes a JavaScript file that defines a global variable with the list of assets to precache.
* This file is intended to be imported or referenced by the service worker.
*
* @param {string} filePath - The path where the output file should be written (e.g., "dist/sw-assets.js")
* @param {AssetEntry[]} assets - The list of assets to inject, each with a `url` and optional `revision`
*/
// Import Node's filesystem module to write files to disk
import fs from 'fs';
export function writeInjectedAssetsFile(filePath, assets) {
// Convert the assets list to a JS assignment as a global variable on the service worker scope
const content = `self.__INJECTED_ASSETS__ = ${JSON.stringify(assets, null, 2)};`;
// Write the content to the specified file
fs.writeFileSync(filePath, content);
}