Msw: Question: How can I prevent mockServiceWorker.js from being added to build folder?

Created on 24 Jul 2020  路  3Comments  路  Source: mswjs/msw

Hi.

I have initialised the mock service worker for browser integration in my React app and is in the public folder. The file states that it shouldn't be deployed to production.

How can I prevent the file from being added to the build when I run npm run build.

Would the service worker start in the browser even though in the index file I only start the worker if the NODE_ENV is not production?

question

All 3 comments

Hey, @PritamSangani.

Although you copy the mockServiceWorker.js file into your public directory, the Service Worker will not get registered automatically. For that you need to explicitly call worker.start() as a part of your application's code.

Would the service worker start in the browser even though in the index file I only start the worker if the NODE_ENV is not production?

No, it wouldn't. The only thing you'd have is a JavaScript file (worker script) that is not used by anything in production.

The worker script is required to be in a public directory in order to be served by your application during development. We've chosen a file copying strategy to give you a transparent control over the script itself, and to better understand where the Service Worker actually is. However, since the worker script is in the public directory, it most likely gets copied to the built version of the application as well. While this has no negative effect on its own (considered you've enabled mocking conditionally in your application's code), it still introduces an unused build file, which may get confusing.

I'm not sure what recommendation to give here. If the unused file annoys you, consider having a cleanup script that runs on CI, so you don't lose the worker script locally each time you build. If you don't mind the file itself, just make sure you are not enabling the mocking on production and you should be fine.

Let me know which solution you choose, I'm curious.

consider having a cleanup script that runs on CI

Hi @kettanaito in my current app I'm following the same strategy to remove before the build it works fine 馃槃

package.json scripts

    "msw:cleanup": "rm public/mockServiceWorker.js",

    "prebuild:ci": "yarn msw:cleanup",
    "build:ci": "yarn build",

I don't think there is more to suggest in this matter, so I'm closing the issue. Please, feel free to discuss here further, I will reopen it in case we come to the conclusion this can be somehow handled as a part of the library's API, but I doubt that. Thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

otaciliolacerda picture otaciliolacerda  路  3Comments

slowselfip picture slowselfip  路  3Comments

dashed picture dashed  路  4Comments

derekr picture derekr  路  3Comments

Afsoon picture Afsoon  路  3Comments