From a17bcd18cce1514485250f2f629e7df13eef3962 Mon Sep 17 00:00:00 2001 From: Artem Zakharchenko Date: Mon, 22 Jan 2024 19:27:13 +0100 Subject: [PATCH] use webpack alias hack to suppress "msw/browser" imports --- examples/with-next/app/mockProvider.tsx | 8 ++++---- examples/with-next/app/movieList.tsx | 6 ++++-- examples/with-next/mocks/handlers.ts | 2 +- examples/with-next/next.config.mjs | 24 +++++++++++++++++++++++- 4 files changed, 32 insertions(+), 8 deletions(-) diff --git a/examples/with-next/app/mockProvider.tsx b/examples/with-next/app/mockProvider.tsx index 391eeec..155bada 100644 --- a/examples/with-next/app/mockProvider.tsx +++ b/examples/with-next/app/mockProvider.tsx @@ -1,11 +1,11 @@ 'use client' import { useEffect, useState } from 'react' -if (typeof window === 'undefined') { - throw new Error('Is not this a browser-only module?') -} +// if (typeof window === 'undefined') { +// throw new Error('Is not this a browser-only module?') +// } -export async function MockProvider({ +export function MockProvider({ children, }: Readonly<{ children: React.ReactNode diff --git a/examples/with-next/app/movieList.tsx b/examples/with-next/app/movieList.tsx index 3249065..7bd73fd 100644 --- a/examples/with-next/app/movieList.tsx +++ b/examples/with-next/app/movieList.tsx @@ -27,7 +27,9 @@ export function MovieList() { }), }) .then((response) => response.json()) - .then((movies) => setMovies(movies)) + .then((response) => { + setMovies(response.data.movies) + }) .catch(() => setMovies([])) } @@ -37,7 +39,7 @@ export function MovieList() { {movies.length > 0 ? ( ) : null} diff --git a/examples/with-next/mocks/handlers.ts b/examples/with-next/mocks/handlers.ts index 10e9cc4..36301c2 100644 --- a/examples/with-next/mocks/handlers.ts +++ b/examples/with-next/mocks/handlers.ts @@ -4,7 +4,7 @@ import type { User } from '../app/page' export const handlers = [ http.get('https://api.example.com/user', () => { return HttpResponse.json({ - firstName: 'John', + firstName: 'Kate', lastName: 'Maverick', }) }), diff --git a/examples/with-next/next.config.mjs b/examples/with-next/next.config.mjs index a37f54b..ac3843a 100644 --- a/examples/with-next/next.config.mjs +++ b/examples/with-next/next.config.mjs @@ -2,7 +2,29 @@ const nextConfig = { experimental: { instrumentationHook: true + }, + webpack(config, { isServer }) { + /** + * @fixme This is completely redundant. webpack should understand + * export conditions and don't try to import "msw/browser" code + * that's clearly marked as client-side only in the app. + */ + if (isServer) { + if (Array.isArray(config.resolve.alias)) { + config.resolve.alias.push({ name: "msw/browser", alias: false }) + } else { + config.resolve.alias["msw/browser"] = false + } + } else { + if (Array.isArray(config.resolve.alias)) { + config.resolve.alias.push({ name: "msw/node", alias: false }) + } else { + config.resolve.alias["msw/node"] = false + } + } + + return config; } -}; +} export default nextConfig;