msw icon indicating copy to clipboard operation
msw copied to clipboard

feat: better esm support

Open ivanhofer opened this issue 3 years ago • 5 comments

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.js instead of 'lib' in a few files (easy to achive)
  • [x] ~tsup does 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

ivanhofer avatar Sep 11 '22 18:09 ivanhofer

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

codesandbox-ci[bot] avatar Sep 11 '22 18:09 codesandbox-ci[bot]

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?

mattcosta7 avatar Sep 12 '22 12:09 mattcosta7

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

ivanhofer avatar Sep 13 '22 16:09 ivanhofer

Nice, work. I was about to open an issue, but it looks like it should be fixed once this PR is merged 😄

filipw01 avatar Sep 20 '22 07:09 filipw01

I think this PR is ready to be merged. Or is something still missing?

ivanhofer avatar Sep 20 '22 13:09 ivanhofer

@kettanaito @ivanhofer is this coming into the next release?

mataspetrikas avatar Sep 29 '22 10:09 mataspetrikas

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...

kettanaito avatar Nov 05 '22 22:11 kettanaito

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.

kettanaito avatar Nov 08 '22 12:11 kettanaito