diff --git a/packages/devkit/src/utils/replace-package.spec.ts b/packages/devkit/src/utils/replace-package.spec.ts index d4ffee7dcdc02..e212a96e39577 100644 --- a/packages/devkit/src/utils/replace-package.spec.ts +++ b/packages/devkit/src/utils/replace-package.spec.ts @@ -165,6 +165,14 @@ describe('replaceNrwlPackageWithNxPackage', () => { }); }); + it('should handle broken package.json files', () => { + tree.write('package.json', '{ broken: "json '); + + expect(() => + replaceNrwlPackageWithNxPackage(tree, 'old-package', 'new-package') + ).not.toThrow(); + }); + it('should replace any mentions in files', () => { expect(tree.read('README.txt').toString()).toContain('new-package'); expect(tree.read('README.txt').toString()).not.toContain('old-package'); diff --git a/packages/devkit/src/utils/replace-package.ts b/packages/devkit/src/utils/replace-package.ts index e9f439db0ca75..2340dde471128 100644 --- a/packages/devkit/src/utils/replace-package.ts +++ b/packages/devkit/src/utils/replace-package.ts @@ -38,20 +38,26 @@ function replacePackageInDependencies( return; } - updateJson(tree, path, (packageJson) => { - for (const deps of [ - packageJson.dependencies ?? {}, - packageJson.devDependencies ?? {}, - packageJson.peerDependencies ?? {}, - packageJson.optionalDependencies ?? {}, - ]) { - if (oldPackageName in deps) { - deps[newPackageName] = deps[oldPackageName]; - delete deps[oldPackageName]; + try { + updateJson(tree, path, (packageJson) => { + for (const deps of [ + packageJson.dependencies ?? {}, + packageJson.devDependencies ?? {}, + packageJson.peerDependencies ?? {}, + packageJson.optionalDependencies ?? {}, + ]) { + if (oldPackageName in deps) { + deps[newPackageName] = deps[oldPackageName]; + delete deps[oldPackageName]; + } } - } - return packageJson; - }); + return packageJson; + }); + } catch (e) { + console.warn( + `Could not replace ${oldPackageName} with ${newPackageName} in ${path}.` + ); + } }); } diff --git a/packages/nx/src/generators/utils/project-configuration.ts b/packages/nx/src/generators/utils/project-configuration.ts index d29c13f081a29..66325cac544b9 100644 --- a/packages/nx/src/generators/utils/project-configuration.ts +++ b/packages/nx/src/generators/utils/project-configuration.ts @@ -218,10 +218,12 @@ function findCreatedProjectFiles(tree: Tree) { if (fileName === 'project.json') { createdProjectFiles.push(change.path); } else if (fileName === 'package.json') { - const contents: PackageJson = JSON.parse(change.content.toString()); - if (contents.nx) { - createdProjectFiles.push(change.path); - } + try { + const contents: PackageJson = JSON.parse(change.content.toString()); + if (contents.nx) { + createdProjectFiles.push(change.path); + } + } catch {} } } }