index.js 1.6 KB

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