From 7e517eef95cc8db289c354c1c37862ab0b10aaa7 Mon Sep 17 00:00:00 2001 From: Colum Ferry Date: Thu, 19 Sep 2024 12:27:42 +0100 Subject: [PATCH] fix(angular): license-webpack-plugin should not scan root package.json #27989 --- .../angular/src/builders/utilities/webpack.ts | 38 ++++++++++++++++++- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/packages/angular/src/builders/utilities/webpack.ts b/packages/angular/src/builders/utilities/webpack.ts index 916cfbdd7cdfa..b12c4c57fedaa 100644 --- a/packages/angular/src/builders/utilities/webpack.ts +++ b/packages/angular/src/builders/utilities/webpack.ts @@ -2,6 +2,7 @@ import { merge } from 'webpack-merge'; import { registerTsProject } from '@nx/js/src/internal'; import { workspaceRoot } from '@nx/devkit'; import { join } from 'path'; +import { existsSync, readFileSync } from 'fs'; export async function mergeCustomWebpackConfig( baseWebpackConfig: any, @@ -22,11 +23,44 @@ export async function mergeCustomWebpackConfig( // The extra Webpack configuration file can export a synchronous or asynchronous function, // for instance: `module.exports = async config => { ... }`. + let newConfig: any; if (typeof config === 'function') { - return config(baseWebpackConfig, options, target); + newConfig = config(baseWebpackConfig, options, target); } else { - return merge(baseWebpackConfig, config); + newConfig = merge(baseWebpackConfig, config); } + + // license-webpack-plugin will at times try to scan the monorepo's root package.json + // This will result in an error being thrown + // Ensure root package.json is excluded + const licensePlugin = newConfig.plugins.find( + (p) => p.constructor.name === 'LicenseWebpackPlugin' + ); + if (licensePlugin) { + let rootPackageJsonName: string; + const pathToRootPackageJson = join( + newConfig.context.root ?? workspaceRoot, + 'package.json' + ); + if (existsSync(pathToRootPackageJson)) { + try { + const rootPackageJson = JSON.parse( + readFileSync(pathToRootPackageJson, 'utf-8') + ); + rootPackageJsonName = rootPackageJson.name; + licensePlugin.pluginOptions.excludedPackageTest = (pkgName: string) => { + if (!rootPackageJsonName) { + return false; + } + return pkgName === rootPackageJsonName; + }; + } catch { + // do nothing + } + } + } + + return newConfig; } export function resolveCustomWebpackConfig(path: string, tsConfig: string) {