合并服务工作者

将 MSW 与现有 Service Worker 一起使用。

浏览器每个范围只能注册一个 Service Worker。这意味着如果你的应用已经注册了 Service Worker,则它无法并行为 MSW 注册另一个。通过合并两个工作脚本,你仍然可以同时使用自定义 Service Worker 和 MSW。

¥The browser can only register a single Service Worker per scope. This means that if your application already registers a Service Worker, it cannot register another one for MSW in parallel. You can still use both your custom Service Worker and MSW by merging the two worker scripts.

Import MSW’s worker in your existing worker

首先,修改你现有的工作程序脚本以有条件地导入 /mockServiceWorker.js。在工作器范围内全局使用 importScripts() API

¥First, modify your existing worker script to conditionally import /mockServiceWorker.js. Use the importScripts() API available globally in the worker’s scope.

// public/existing-worker.js
const url = new URL(location.href)
 
if (url.searchParams.get('enableApiMocking') === 'true') {
  importScripts('/mockServiceWorker.js')
}
 
// The rest of your Service Worker script here.
// self.addEventListener('fetch', listener)

Enable API mocking conditionally

// src/app.js
const workerUrl = new URL('/existing-worker.js', location.origin)
 
// In your application code, set the "enableApiMocking" search parameter
// on the worker script URL. This way the client lets the worker know
// whether it should import MSW's worker script based on the environment.
if (process.env.NODE_ENV === 'development') {
  workerUrl.searchParams.set('enableApiMocking', 'true')
}
 
navigator.serviceWorker.register(workerUrl.href)

Set up MSW to use your worker

最后,在 worker.start() 调用中提供你的 worker 脚本 URL 作为 serviceWorker.url 选项。由于你注册的唯一 Service Worker 是你的自定义 Worker,因此让 MSW 知道它应该使用它来控制网络。

¥Lastly, provide your worker script URL as the serviceWorker.url option on the worker.start() call. Since the only Service Worker you register is your custom worker, let MSW know that it should use it to control the network.

worker.start({
  serviceWorker: {
    url: '/existing-worker.js',
  },
})