From 25035927d69f45abaa23afd59b3c6548eac402b6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leosvel=20P=C3=A9rez=20Espinosa?= Date: Mon, 9 May 2022 15:43:54 +0100 Subject: [PATCH] fix(angular): handle packages with no exported package.json when collecting secondary entry points for mf builds (#10216) --- .../angular/src/utils/mfe/mfe-webpack.spec.ts | 19 +++++++++++++++++ packages/angular/src/utils/mfe/mfe-webpack.ts | 21 +++++++++++++++---- 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/packages/angular/src/utils/mfe/mfe-webpack.spec.ts b/packages/angular/src/utils/mfe/mfe-webpack.spec.ts index 4ac20e9b686c1..69972faaf1515 100644 --- a/packages/angular/src/utils/mfe/mfe-webpack.spec.ts +++ b/packages/angular/src/utils/mfe/mfe-webpack.spec.ts @@ -231,6 +231,25 @@ describe('MFE Webpack Utils', () => { }, }); }); + + it('should not throw when the main entry point package.json cannot be required', () => { + // ARRANGE + (fs.existsSync as jest.Mock).mockImplementation( + (file) => !file.endsWith('non-existent-top-level-package/package.json') + ); + jest.spyOn(devkit, 'readJsonFile').mockImplementation((file) => ({ + name: file + .replace(/\\/g, '/') + .replace(/^.*node_modules[/]/, '') + .replace('/package.json', ''), + dependencies: { '@angular/core': '~13.2.0' }, + })); + + // ACT & ASSERT + expect(() => + sharePackages(['non-existent-top-level-package']) + ).not.toThrow(); + }); }); }); diff --git a/packages/angular/src/utils/mfe/mfe-webpack.ts b/packages/angular/src/utils/mfe/mfe-webpack.ts index d3f0cd36adf30..bf030358e2d73 100644 --- a/packages/angular/src/utils/mfe/mfe-webpack.ts +++ b/packages/angular/src/utils/mfe/mfe-webpack.ts @@ -137,10 +137,23 @@ function collectPackageSecondaryEntryPoints( pkgVersion: string, collectedPackages: { name: string; version: string }[] ): void { - const packageJsonPath = require.resolve(`${pkgName}/package.json`, { - paths: [workspaceRoot], - }); - const pathToPackage = dirname(packageJsonPath); + let pathToPackage: string; + try { + const packageJsonPath = require.resolve(`${pkgName}/package.json`, { + paths: [workspaceRoot], + }); + pathToPackage = dirname(packageJsonPath); + } catch { + // the package.json might not resolve if the package has the "exports" + // entry and is not exporting the package.json file, fall back to trying + // to find it from the top-level node_modules + pathToPackage = join(workspaceRoot, 'node_modules', pkgName); + if (!existsSync(join(pathToPackage, 'package.json'))) { + // might not exist if it's nested in another package, just return here + return; + } + } + const subDirs = getNonNodeModulesSubDirs(pathToPackage); recursivelyCollectSecondaryEntryPointsFromDirectory( pkgName,