如何将 Service Worker 库 (MSW) 与 Parcel bundler 结合使用

问题描述

我有一个使用 Parcel 捆绑的小型 TypeScript React 项目。我想为模拟服务器请求添加 MSW,但我无法让它工作。

我有一个非常简约的包裹设置:

"scripts": {
  "start": "parcel index.html","build": "parcel build index.html"
},

至于 MSW,一切都按照他们的 documentation 进行。以下是 service-worker 的启动方式:

if (process.env.NODE_ENV === "development") {
  const { worker } = require("./mocks/browser")
  worker.start()
}

与 Webpack 捆绑时,完全相同的实现完美地工作。但在 Parcel 中,它会导致控制台出现以下错误

The script has an unsupported MIME type ('text/html').

[MSW] Failed to register a Service Worker: Failed to register a ServiceWorker for scope ('http://localhost:1234/') with script ('http://localhost:1234/mockServiceWorker.js'): The script has an unsupported MIME type ('text/html').

有没有办法让它工作?

解决方法

事实证明,我使用 npx msw init 运行 public,它适用于 Create-React-App,而不是我在使用 Parcel 时应该使用的 dist