index.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. let globalPnpApi;
  2. try {
  3. globalPnpApi = require(`pnpapi`);
  4. } catch {
  5. // Just ignore if we don't have a global PnP instance - perhaps
  6. // we'll eventually find one at runtime due to multi-tree
  7. }
  8. const createRequire = require(`./createRequire`);
  9. const getDefaultResolver = require(`./getDefaultResolver`);
  10. module.exports = (request, options) => {
  11. const {
  12. basedir,
  13. defaultResolver = getDefaultResolver(),
  14. extensions,
  15. } = options;
  16. if (process.versions.pnp) {
  17. let pnpApi = globalPnpApi;
  18. // While technically it would be more correct to run this code
  19. // everytime (since they file being run *may* belong to a
  20. // different dependency tree than the one owning Jest), in
  21. // practice this doesn't happen anywhere else than on the Jest
  22. // repository itself (in the test env). So in order to preserve
  23. // the performances, we can afford a slight incoherence here.
  24. if (!pnpApi) {
  25. try {
  26. const baseReq = createRequire(`${basedir}/internal.js`);
  27. pnpApi = baseReq(`pnpapi`);
  28. } catch {
  29. // The file isn't part of a PnP dependency tree, so we can
  30. // just use the default Jest resolver.
  31. }
  32. }
  33. if (pnpApi) {
  34. const resolution = pnpApi.resolveRequest(request, `${basedir}/`, {extensions});
  35. // When the request is a native module, Jest expects to get the string back unmodified, but pnp returns null instead.
  36. if (resolution === null)
  37. return request;
  38. return resolution;
  39. }
  40. }
  41. return defaultResolver(request, {...options, allowPnp: false});
  42. };