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

Imports and requires may not be using Node Loaders/Registration for ESM #120

Open
Downchuck opened this issue Nov 20, 2024 · 1 comment
Open

Comments

@Downchuck
Copy link

The Yarn PNP mechanism uses loaders and/or registration for CJS and ESM support.

Presently using -r .pnp.cjs works appropriately in AWS SAM but using --loader runs into a host of issues as detailed in:

yarnpkg/berry#6604

I'm not clear why the two are not working together, as they work in other contexts - but in the AWS SAM index.mjs it seems that the tryRequire path goes through a route where pnp.setup(); is unable to monkey patch calls once it is working within the CJS loader by route of the ESM loader.

@Downchuck
Copy link
Author

Downchuck commented Nov 20, 2024

Cross posting the current work-around as a loader, using -r /opt/nodejs/.pnp.cjs --loader /var/task/hackey-hack.mjs:

/*
- Our .pnp.loader.mjs uses the parentURL, to try to pickup .pnp.cjs which fails.
- It does not seem to use any of our env variables to set the yarn cache either.
- Pretend we are in /opt/nodejs/ so it picks up .pnp.cjs and the .yarn folder.
*/
const esmpnp = await import("/opt/nodejs/.pnp.loader.mjs");

export async function resolve(specifier, context, nextResolve) {
  const parentURL = context.parentURL?.replace("file:///var/task/", "file:///opt/nodejs/");
  const contexts = { ...context, parentURL };
  const resolve = await esmpnp.resolve(specifier, specifier.startsWith("./") ? context : contexts, nextResolve);
  return resolve;
}

export async function load(urlString, context, nextLoad) {
  const load = await esmpnp.load(urlString, context, nextLoad);
  if(urlString === "file:///var/runtime/index.mjs") {
    const prepend = 'const { default: pnp } = await import("/opt/nodejs/.pnp.cjs"); pnp.setup(); const esmpnp = await import("/opt/nodejs/.pnp.loader.mjs");';   
    load.source = prepend + "\n" + load.source;
  }
  return load;
}

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