diff --git a/CHANGELOG.md b/CHANGELOG.md index a28484a..c938828 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [2.1.3] - 2022-06-03 + +### Fixed + +- Fixes #204 Hardcoded service_worker file breaks when using custom service_worker (Thanks @j1mie) + ## [2.1.2] - 2022-04-19 ### Fixed diff --git a/package.json b/package.json index ede09c4..712a058 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@webextension-toolbox/webpack-webextension-plugin", - "version": "2.1.2", + "version": "2.1.3", "description": "Webpack plugin that compiles web-extension manifest.json files and adds smart auto reload", "main": "./dist/index.js", "types": "./dist/index.d.ts", diff --git a/src/plugin/index.ts b/src/plugin/index.ts index d179e7f..e66d37b 100644 --- a/src/plugin/index.ts +++ b/src/plugin/index.ts @@ -148,16 +148,32 @@ export default class WebextensionPlugin { * @param {Object} compilation */ compilation(compilation: Compilation) { - this.injectClient(compilation); + this.injectServiceWorkerClient(compilation); this.keepFiles(compilation); } /** - * Inject Client into the current server_worker + * Inject Service Worker Client into the current server_worker * @param compilation */ - injectClient(compilation: Compilation) { - if (this.autoreload && this.isWatching && !this.clientAdded) { + injectServiceWorkerClient(compilation: Compilation) { + // Locate the service worker + const manifestPath = path.join( + compilation.options.context ?? "", + this.manifestNameDefault + ); + const manifestBuffer = readFileSync(manifestPath, { + encoding: "utf8", + }); + const manifest = JSON.parse(manifestBuffer); + const serviceWorker = manifest?.background?.service_worker ?? null; + + if ( + serviceWorker !== null && + this.autoreload && + this.isWatching && + !this.clientAdded + ) { const { name } = this.constructor; compilation.hooks.processAssets.tap( { @@ -165,7 +181,7 @@ export default class WebextensionPlugin { stage: Compilation.PROCESS_ASSETS_STAGE_ADDITIONS, }, (assets) => { - if (assets["scripts/service_worker.js"]) { + if (assets[serviceWorker]) { const source = readFileSync( path.resolve(__dirname, "service_worker.js"), { @@ -180,7 +196,7 @@ export default class WebextensionPlugin { }); compilation.updateAsset( - "scripts/service_worker.js", + serviceWorker, (old) => new this.sources.RawSource(`${replacedSource}\n${old.source()}`) );