使用自定义 "homepage" 属性

package.json 中使用自定义 homepage 属性时,你可能会遇到 Service Worker 注册问题。考虑以下 package.json

¥When using a custom homepage property in your package.json, you may encounter Service Worker registration issues. Consider the following package.json:

// package.json
{
  "homepage": "/my-app"
}

这将把 /my-app 路径视为应用的主目录。但是,MSW 仍希望你在根目录下提供工作脚本。

¥This will treat the /my-app path as the home directory for your application. However, MSW will still expect you to serve the worker script at the root.

为了解决这个问题,你必须在启动工作器时提供一个明确的 Service Worker URL 作为 serviceWorker.url 选项:

¥To account for that, you have to provide an explicit Service Worker URL as the serviceWorker.url option when starting the worker:

// src/index.js
// Read the package.json file to grab the "homepage" value.
import packageJson from '../package.json'
 
if (process.env.NODE_ENV === 'development') {
  const { worker } = await import('./mocks/browser')
 
  await worker.start({
    serviceWorker: {
      // Provide a custom worker script URL, taking
      // the "homepage" into account.
      url: `${packageJson.homepage}/mockServiceWorker.js`,
    },
  })
}