feat: better esm support
fixes #1267
I have investigated #1267 a bit. There are a few road blocks to make msw/node work in a .mjs file:
- [x] reference
lib/index.jsinstead of'lib'in a few files (easy to achive) - [x] ~
tsupdoes not support import assertions (needed here https://github.com/mswjs/msw/blob/main/src/context/status.ts#L1) https://github.com/egoist/tsup/issues/714~ workaround: https://github.com/mswjs/msw/pull/1399#discussion_r968360168 - [x] ~dynamic import of
node-fetch(https://github.com/mswjs/msw/blob/main/src/context/fetch.ts#L6) is not supported in esm context. https://github.com/evanw/esbuild/issues/1921~ workaround: https://github.com/mswjs/msw/pull/1399#issuecomment-1243681143
This pull request is automatically built and testable in CodeSandbox.
To see build info of the built libraries, click here or the icon next to each commit SHA.
Latest deployment of this branch, based on commit 2755f43ce12fad2e771be35a080f823a05a6c104:
| Sandbox | Source |
|---|---|
| MSW React | Configuration |
dynamic import of node-fetch
I think we could get around this with something like
useFetch = isNodeProcess() ? (input, init) => import('node-fetch').then(({default: nodeFetch}) => fetch(input, init)) : window.fetch
I'm curious if we could also avoid using node-fetch directly in this library and just stipulate that globalThis.fetch be defined already (via a user polyfill) instead?
With this branch it is now poosible to run the following esm file:
test.mjs
import { setupServer } from 'msw/node'
setupServer()
with the command
node ./test.mjs
Nice, work. I was about to open an issue, but it looks like it should be fixed once this PR is merged 😄
I think this PR is ready to be merged. Or is something still missing?
@kettanaito @ivanhofer is this coming into the next release?
The only thing I'd add is an automated test for the distributed ESM format. Let me see if I can dig out the previous test I've written...
Released: v0.48.0 🎉
This has been released in v0.48.0!
Make sure to always update to the latest version (npm i msw@latest) to get the newest features and bug fixes.
Predictable release automation by @ossjs/release.