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されている
調査
色々調べていたら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の設定を書き加えて解決した。
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;