如何在Parcel bundler中使用service worker库(MSW)



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

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

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

至于MSW,一切都是根据他们的文档完成的。下面是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 dist

事实证明,我运行npx msw initpublic,适用于Create-React-App,而不是dist,因为我应该使用包裹。

最新更新