我正在尝试使用 msw 来运行带有模拟数据的 React 应用程序。下面是我的 index.js;
import React from 'react';
import * as serviceWorker from './serviceWorker';
if (process.env.NODE_ENV === 'development') {
const { worker } = require('./mocks/browser')
worker.start().then(() => renderApp())
}
我的服务工作者 js 位于 public/mockServiceWorker.js
我的 src/mocks/browser.js 如下;
import { setupWorker } from 'msw'
import { handlers } from './handlers'
// This configures a Service Worker with the given request handlers.
export const worker = setupWorker(...handlers)
我的 src/mocks/index.js 如下;
if (typeof window === "undefined") {
const { server } = require("mocks/server");
server.listen();
} else {
const { worker } = require("mocks/browser");
worker.start();
}
现在在浏览器中运行应用程序时,我看到以下错误;
Failed to register a ServiceWorker for scope ('http://localhost:3000/') with script ('http://localhost:3000/mockServiceWorker.js'): The script has an unsupported MIME type ('text/html').
我也有点困惑,因为我看到在 src 下创建了一个额外的 serviceWorker.js(这似乎是通过 create-react-app 生成的),正如你在上面看到的,这也是在 src/index.js 中导入的(再次通过 create-react-app) ,但我希望使用的是 public/mockServiceWorker.js
我不确定这些是否无关。我正在尝试遵循https://github.com/ghoshnirmalya/introduction-to-msw上的示例
还有 MSW 官方页面供参考 - https://mswjs.io/docs/getting-started/integrate/browser