[mocks] fails to load service work on subfolders
Hi! 👋
Firstly, thanks for your work on this project! 🙂
Today I used patch-package to patch @web/[email protected] for the project I'm working on.
When using mocking on subfolders e.g. you have
index.html
list/list.demo.html
detail/detail.demo.html
now using mocks on index.html works fine but as soon as you want to open up list/list.html then it tries to search for the __msw_sw__js at http://localhost:8000/list/__msw_sw__js which then returns a 404.
adjusting the plugin to always serve the same SW for every __msw_sw__js request makes it work.
PS: alternatively the "resolve" logic to the service worker url in msw itself could be adjusted but there could be cases where different urls use different SWs so maybe doing like suggested is best? 🤔
Here is the diff that solved my problem:
diff --git a/node_modules/@web/mocks/wds-plugin.js b/node_modules/@web/mocks/wds-plugin.js
index d16e64a..03b4d86 100644
--- a/node_modules/@web/mocks/wds-plugin.js
+++ b/node_modules/@web/mocks/wds-plugin.js
@@ -11,7 +11,7 @@ export function mockPlugin() {
* @param {import('koa').Context} context
*/
serve(context) {
- if (context.request.url === '/__msw_sw__.js') {
+ if (context.request.url.endsWith('__msw_sw__.js')) {
const serviceWorkerPath = path.resolve(__dirname, './sw.js');
return readFileSync(serviceWorkerPath, 'utf8');
}
This issue body was partially generated by patch-package.
hmm maybe a better fix is to set the browser url?
serviceWorker: {
- url: '__msw_sw__.js',
+ url: '/__msw_sw__.js',
here
https://github.com/modernweb-dev/web/blob/d6a6112bc6c038fa6be6937e9e66b5d9c44476d3/packages/mocks/browser.js#L9
Ran into this myself the other day, changing to '/__msw_sw__.js' indeed fixed it
Need to double check if this also works for the build though