Skip to content

Commit

Permalink
Fixes #204 determine service_worker path from manifest
Browse files Browse the repository at this point in the history
  • Loading branch information
tm1000 committed Jun 3, 2022
1 parent 4639c4f commit d7d7709
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 7 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
28 changes: 22 additions & 6 deletions src/plugin/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,24 +148,40 @@ 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(
{
name,
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"),
{
Expand All @@ -180,7 +196,7 @@ export default class WebextensionPlugin {
});

compilation.updateAsset(
"scripts/service_worker.js",
serviceWorker,
(old) =>
new this.sources.RawSource(`${replacedSource}\n${old.source()}`)
);
Expand Down

0 comments on commit d7d7709

Please sign in to comment.