4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

記事投稿キャンペーン 「2024年!初アウトプットをしよう」

Next.jsでMSWを導入しようとしたら苦戦した

Last updated at Posted at 2024-01-06

MSW(Mock Service Worker)とは

APIモッキングライブラリ
Service Workerを使ってリクエストをインターセプトし、事前にモック化したレスポンスを返す。

Next.jsで導入

https://mswjs.io/docs/getting-started
こちらの手順に沿って一通り設定を終え、
いざローカルを立ち上げようとするとエラーが出る。

Module not found: Package path ./browser is not exported from package /xxxxxx/node_modules/msw (see exports field in /xxxxxx/node_modules/msw/package.json)

対象のファイルを見にいってもちゃんとexportされている:thinking:

調査

色々調べていたらissue発見
https://github.com/mswjs/msw/issues/1801

原因

The error happens during build time (not runtime). None of nodeHelpers are never called in browser and they are not even included in browser bundle thanks to tree-shaking. Webpack though still needs to go through them during build and because of ./node being blocked in browser it errors as it can't find the entry point.

mswでこれを解決することはなさそうで、closeされてた。

I'm fairly confident our exports are correctly written. We forbid msw/node imports in the browser and msw/browser imports in Node.js. In the end, it's your framework's compiler that evaluates those, and so it must be configured correctly by the framework to understand what modules should use what export condition.

解決

next.config.jsにwebpackの設定を書き加えて解決した。

next.config.js
const nextConfig = {
	...
	webpack: (config, { isServer }) => {
		if (isServer) {
			// next server build => ignore msw/browser
			if (Array.isArray(config.resolve.alias)) {
				config.resolve.alias.push({
					name: 'msw/browser',
					alias: false,
				});
			} else {
				config.resolve.alias['msw/browser'] = false;
			}
		} else {
			// browser => ignore msw/node
			if (Array.isArray(config.resolve.alias)) {
				config.resolve.alias.push({ name: 'msw/node', alias: false });
			} else {
				config.resolve.alias['msw/node'] = false;
			}
		}
		return config;
	},
    ....
};

module.exports = nextConfig;

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?