Skip to content

Commit

Permalink
using pnpify to fix typescript module resolution
Browse files Browse the repository at this point in the history
  • Loading branch information
Leighton Smith committed Oct 21, 2019
1 parent 13f2934 commit 62b1926
Showing 1 changed file with 58 additions and 0 deletions.
58 changes: 58 additions & 0 deletions pnpify.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
let pnp;
try {
// If we're in PnP, run pnpify so typescript thinks it's fetching
// absolute imports from node_modules/ rather than the yarn cache.
pnp = require(`pnpapi`);
const pnpify = require(`@yarnpkg/pnpify`);
pnpify.patchFs();
} catch (error) {
// not in PnP; not a problem
}

function resolveModuleName(request, issuer, compilerOptions, moduleResolutionHost, parentResolver) {

const topLevelLocation = pnp.getPackageInformation(pnp.topLevel).packageLocation;

const [, prefix = ``, packageName = ``, rest] = request.match(/^(!(?:.*!)+)?((?!\.{0,2}\/)(?:@[^\/]+\/)?[^\/]+)?(.*)/);


let failedLookupLocations = [];

// First we try the resolution on "@types/package-name" starting from the project root
if (packageName) {
const typesPackagePath = `@types/${packageName.replace(/\//g, `__`)}${rest}`;

const finalResolution = parentResolver(typesPackagePath, issuer, compilerOptions, moduleResolutionHost);

if (finalResolution.resolvedModule || finalResolution.resolvedTypeReferenceDirective) {
return finalResolution;
} else {
failedLookupLocations = failedLookupLocations.concat(finalResolution.failedLookupLocations);
}
}

// Then we try on "package-name", this time starting from the package that makes the request
if (true) {
const regularPackagePath = `${packageName || ``}${rest}`;

const finalResolution = parentResolver(regularPackagePath, issuer, compilerOptions, moduleResolutionHost);

if (finalResolution.resolvedModule || finalResolution.resolvedTypeReferenceDirective) {
return finalResolution;
} else {
failedLookupLocations = failedLookupLocations.concat(finalResolution.failedLookupLocations);
}
}

return {
resolvedModule: undefined,
resolvedTypeReferenceDirective: undefined,
failedLookupLocations,
};
}

module.exports.resolveModuleName = pnp
? resolveModuleName
: (moduleName, containingFile, compilerOptions, compilerHost, resolveModuleName) =>
resolveModuleName(moduleName, containingFile, compilerOptions, compilerHost);

0 comments on commit 62b1926

Please sign in to comment.