Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support import and require #25

Open
theahura opened this issue May 12, 2023 · 3 comments
Open

Support import and require #25

theahura opened this issue May 12, 2023 · 3 comments

Comments

@theahura
Copy link

I'm using jsdom-worker to support third party libs that use service workers in a jest runtime. The third party lib uses require all over the place, which causes issues when jest is otherwise configured as a module (i.e. using import). One way to solve this is to polyfill require -- for example, https://stackoverflow.com/a/71883023/3269537

import { createRequire } from "module";
const require = createRequire(import.meta.url);

It would be really convenient if jsdom-worker supported both require and import, so that it is agnostic to what code is actually being loaded. Can we simply inject the above here: https://github.com/developit/jsdom-worker/blob/main/src/index.js#L129? Happy to send out a pr that tries this

@theahura
Copy link
Author

Update: gave this a shot, ran into some issues. Because this library uses the Function object constructor to generate the code from string, it's using CommonJS regardless of what runtime you're actually configuring. This means that import * as foo from 'foo' as well as require(foo) don't work

@theahura
Copy link
Author

You can create a require function with the following in common.js:

const createRequire = import('module').createRequire; const require = createRequire(__filename);

@theahura
Copy link
Author

Still couldn't quite get this working, left the trail here: https://stackoverflow.com/questions/76240658/use-require-or-import-instead-exec-or-the-function-constructor

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant