Skip to content

Commit

Permalink
use webpack alias hack to suppress "msw/browser" imports
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito committed Jan 22, 2024
1 parent f45cce8 commit eb017b0
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 12 deletions.
6 changes: 1 addition & 5 deletions examples/with-next/app/mockProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
'use client'
import { useEffect, useState } from 'react'

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
Expand Down
6 changes: 4 additions & 2 deletions examples/with-next/app/movieList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ export function MovieList() {
}),
})
.then((response) => response.json())
.then((movies) => setMovies(movies))
.then((response) => {
setMovies(response.data.movies)
})
.catch(() => setMovies([]))
}

Expand All @@ -37,7 +39,7 @@ export function MovieList() {
{movies.length > 0 ? (
<ul>
{movies.map((movie) => (
<li id={movie.id}>{movie.title}</li>
<li key={movie.id}>{movie.title}</li>
))}
</ul>
) : null}
Expand Down
2 changes: 1 addition & 1 deletion examples/with-next/mocks/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import type { User } from '../app/page'
export const handlers = [
http.get<never, never, User>('https://api.example.com/user', () => {
return HttpResponse.json({
firstName: 'John',
firstName: 'Kate',
lastName: 'Maverick',
})
}),
Expand Down
30 changes: 26 additions & 4 deletions examples/with-next/next.config.mjs
Original file line number Diff line number Diff line change
@@ -1,8 +1,30 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
experimental: {
instrumentationHook: true
}
};
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
}
}

export default nextConfig;
return config
},
}

export default nextConfig

0 comments on commit eb017b0

Please sign in to comment.