Nuxt3とMSWで「The script has an unsupported MIME type ('text/html')」が出た

間違い

間違いは$ msw init src/static --savesrc/static)していたことだった。 Nuxt2のプロジェクトのひとつではsrc/staticで成功していたので、油断していた。

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

今回のプロジェクトではSPAを採用しているので、MSWで定義した/mock/fooエンドポイントで404のhtmlが取れてしまって、text/htmlと言われていた。

修正

公式ドキュメントの'Where is my "public" directory?'に書いてある通り、Vue.jsでは./publicmockServiceWorker.jsを配置する。

今回のプロジェクトではpublicディレクトリが、都合上./srcの上にあるので、下記コマンドを実行する。

$ npx msw init src/public --save

これで正しく/mock/fooが叩けるようになった。

おまけ

またコンポーネントが/mock/fooを叩く前にworker.start()が完了していて欲しいので、当該Nuxt3プラグインでawait worker.start(...)してあげると、必ず失敗しなくなります。

diff --git a/src/plugins/mockServer.ts b/src/plugins/mockServer.ts
index 692bc21..f7fbfcb 100644
--- a/src/plugins/mockServer.ts
+++ b/src/plugins/mockServer.ts
@@ -1,8 +1,8 @@
 import { worker } from '@/mocks/browser'
 
-export default defineNuxtPlugin(async ({ $config }) => {
+export default defineNuxtPlugin(({ $config }) => {
   if ($config.NUXT_ENV_API_PREFIX === '/mock') {
-    await worker.start({
+    worker.start({
       // モックAPIサーバーで定義されたエンドポイント以外にアクセスした場合に、警告しない
       // https://mswjs.io/docs/api/setup-worker/start#onunhandledrequest
       onUnhandledRequest: 'bypass',

筆者プロフィール

my-latest-logo

aiya000(あいや)

せつラボ 〜圏論の基本〜」 「せつラボ2~雲と天使と関手圏~」 「矢澤にこ先輩といっしょに代数!」を書いています!

強い静的型付けとテストを用いて、バグを防ぐのが好き。Haskell・TypeScript。