UNPKG

siegel

Version:

Web application development ecosystem

25 lines (24 loc) 1.04 kB
import fs from 'fs'; import path from 'path'; import webpack from 'webpack'; import ts from 'typescript'; const { sources, Compilation } = webpack; const NAME = 'siegel-sw-plugin'; const serviceWorkerPlugin = function (entry) { const filename = path.basename(entry); const swContent = fs.readFileSync(entry, 'utf8'); this.apply = function (compiler) { compiler.hooks.thisCompilation.tap(NAME, compilation => { compilation.hooks.processAssets.tap({ name: NAME, stage: Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE }, assets => { const SW_ASSETS = JSON.stringify(Object.keys(assets)); const isTS = filename.endsWith('.ts'); const SW_SOURCE = `const buildOutput=${SW_ASSETS};${isTS ? ts.transpile(swContent) : swContent}`; compilation.emitAsset(isTS ? filename.replace('.ts', '.js') : filename, new sources.RawSource(SW_SOURCE, true)); }); }); }; }; export default serviceWorkerPlugin;