msw-2-upgrade-recipe
Transform MSW v1 code to v2 patterns
Installation
bash
Usage
This codemod transforms TypeScript code by upgrading your project from MSW v1 to v2. The codemod automatically handles all major breaking changes:
- Updates import statements to new locations and names
- Fixes generic type arguments order
- Modernizes request object usage patterns
- Replaces ctx.fetch() with new fetch(bypass()) pattern
- Updates passthrough method calls
- Converts response patterns to new HttpResponse API
- Updates handler callback signatures
- Modernizes event callback signatures
- Replaces deprecated handler printing methods
Transformations Applied
1. Import Updates (imports)
Updates import statements to match MSW v2 locations and naming:
- rest → http
- RestHandler → HttpHandler
- setupWorker now imported from msw/browser
Before:
typescript
After:
typescript
2. Context Fetch (ctx-fetch)
Replaces ctx.fetch(req) with fetch(bypass(req)):
Before:
typescript
After:
typescript
3. Request Passthrough (req-passthrough)
Updates passthrough calls to use the exported function:
Before:
typescript
After:
typescript
4. Request Changes (request-changes)
Modernizes request object usage patterns:
- req.url → new URL(request.url)
- req.params → direct destructuring from callback argument
- req.cookies → direct destructuring from callback argument
- req.body → removed (use request.json() instead)
Before:
typescript
After:
typescript
5. Response Usage (response-usages)
Converts old response patterns to new HttpResponse API:
Before:
typescript
After:
typescript
6. Callback Signature (callback-signature)
Updates handler callback signatures and removes unused variables:
Before:
typescript
After:
typescript
7. Lifecycle Events (lifecycle-events-signature)
Updates lifecycle event callback signatures:
Before:
typescript
After:
typescript
8. Print Handlers (print-handler)
Replaces deprecated printHandlers() with new method:
Before:
typescript
After:
typescript
9. Type Arguments (type-args)
Fixes generic type argument order for type safety:
Before:
typescript
After:
typescript
Important Notes
⚠️ Custom Factory Functions: This codemod does not change signatures of MSW handlers when called through custom factory functions. You'll need to update these manually.
⚠️ Request Body Usage: If you were using req.body, the codemod assumes you want await request.json(). You may need to adjust for other body types manually.
⚠️ Complete Migration: This codemod performs all necessary transformations in the correct order to ensure your code properly migrates to MSW v2.
Development
bash
Resources
License
MIT