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

fix(utils): Fix loadModule when using PnP #4077

Closed
wants to merge 3 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 4 additions & 19 deletions packages/utils/src/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,32 +25,17 @@ export function dynamicRequire(mod: any, request: string): any {

/**
* Helper for dynamically loading module that should work with linked dependencies.
* The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`
* This is equivalent of using `require(require.resolve(moduleName, { paths: [cwd()] }))`
* However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during
* build time. `require.resolve` is also not available in any other way, so we cannot create,
* a fake helper like we do with `dynamicRequire`.
*
* We always prefer to use local package, thus the value is not returned early from each `try/catch` block.
* That is to mimic the behavior of `require.resolve` exactly.
* build time.
*
* @param moduleName module name to require
* @returns possibly required module
*/
export function loadModule<T>(moduleName: string): T | undefined {
let mod: T | undefined;

try {
mod = dynamicRequire(module, moduleName);
return dynamicRequire(require.main, moduleName);
} catch (e) {
// no-empty
return undefined;
}

try {
const { cwd } = dynamicRequire(module, 'process');
mod = dynamicRequire(module, `${cwd()}/node_modules/${moduleName}`) as T;
} catch (e) {
// no-empty
}

return mod;
}