[[MSW]]を使ってみた。せっかくなので[[Nuxt3]]で。 ## プロジェクト作成 ```console $ npx nuxi init nuxt3-boilerplate Need to install the following packages: nuxi Ok to proceed? (y) y Nuxt CLI v3.0.0-rc.3 19:40:05 i cloned nuxt/starter#v3 to C:/Users/tadashi-aikawa/git/github.com/tadashi-aikawa/nuxt3-boilerplate 19:40:07 19:40:07 ✨ Your praiseworthy Nuxt project is just created! Next steps: 📁 cd nuxt3-boilerplate 19:40:07 💿 Install dependencies with npm install or yarn install or pnpm install --shamefully-hoist 19:40:07 🚀 Start development server with npm run dev or yarn dev or pnpm run dev $ cd nuxt3-boilerplate $ npm i ``` 動作確認。 ```console $ npm run dev -- -o ``` `localhost:3000`にアクセスして表示されればOK。 > [!hint]- `-o` は自動でブラウザを開くオプション ### [[Prettier]]インストール ```console npm i -D prettier ``` ## [[MSW]]インストール https://mswjs.io/docs/getting-started/install ```console npm install msw --save-dev ``` ## [[MSW]]でモックを作成 - https://mswjs.io/docs/getting-started/mocks `mocks/handlers.js`を作成する。 - https://mswjs.io/docs/getting-started/mocks/rest-api ```js import { rest } from "msw"; export const handlers = [ rest.get("/ping", (req, res, ctx) => { return res(ctx.status(200), ctx.json({ ping: "poooooooooooooooooooong!" })); }), ]; ``` ## ブラウザでモックを使用する ### [[Service Worker]]のコードを自動生成する https://mswjs.io/docs/getting-started/integrate/browser [[Service Worker]]のコードを`public`配下に作成する。 ```console $ npx msw init public --save Initializing the Mock Service Worker at "C:\Users\tadashi-aikawa\git\github.com\tadashi-aikawa\nuxt3-boilerplate\public"... Service Worker successfully created! C:\Users\tadashi-aikawa\git\github.com\tadashi-aikawa\nuxt3-boilerplate\public\mockServiceWorker.js Continue by creating a mocking definition module in your application: https://mswjs.io/docs/getting-started/mocks INFO In order to ease the future updates to the worker script, we recommend saving the path to the worker directory in your package.json. Writing "msw.workerDirectory" to "C:\Users\tadashi-aikawa\git\github.com\tadashi-aikawa\nuxt3-boilerplate\package.json"... ``` `public/mockServiceWorker.js`ができる。 ### [[Service Worker]]を設定する https://mswjs.io/docs/getting-started/integrate/browser [[Service Worker]]の起動スクリプトを`mocks/browser.js`に書く。 ```js import { setupWorker } from "msw"; import { handlers } from "./handlers"; export const worker = setupWorker(...handlers); ``` `app.vue`の`<script>`に以下を追記。 ```ts <script setup lang="ts"> import Hello from "~/Hello.vue"; import { worker } from "./mocks/browser"; worker.start(); </script> ``` これで実行するとエラーになる。 ``` [nuxt] [request error] require is not defined in ES module scope, you can use import instead ``` ==ここでリタイア..==。[[MSW]]が[[ESモジュール (JavaScript)|ESモジュール]]に対応されていない気がする..。