diff --git a/packages/devkit/src/utils/add-plugin.spec.ts b/packages/devkit/src/utils/add-plugin.spec.ts index 12d214b0a8..70c8d547ea 100644 --- a/packages/devkit/src/utils/add-plugin.spec.ts +++ b/packages/devkit/src/utils/add-plugin.spec.ts @@ -431,6 +431,32 @@ describe('addPlugin', () => { 'echo "Typechecking..." && nx build -p tsconfig.lib.json && nx build -p tsconfig.spec.json && echo "Done"' ); }); + + it('should not touch the package.json when there are no changes to make', async () => { + // package.json with mixed/bad indentation and array value in a single line + // JSON serialization would have a standard indentation and would expand the array value into multiple lines + const packageJsonContent = `{ + "name": "app1", + "scripts": { + "build": "tsc --build" + }, + "keywords": ["foo", "bar", "baz"] +}`; + tree.write('app1/package.json', packageJsonContent); + + await addPlugin( + tree, + graph, + '@nx/next/plugin', + createNodes, + { + targetName: ['build'], + }, + true + ); + + expect(tree.read('app1/package.json', 'utf-8')).toBe(packageJsonContent); + }); }); }); diff --git a/packages/devkit/src/utils/add-plugin.ts b/packages/devkit/src/utils/add-plugin.ts index f4dc447237..09a3d772cd 100644 --- a/packages/devkit/src/utils/add-plugin.ts +++ b/packages/devkit/src/utils/add-plugin.ts @@ -233,7 +233,7 @@ function processProject( return; } - const replacedTargets = new Set(); + let hasChanges = false; for (const targetCommand of targetCommands) { const { command, target, configuration } = targetCommand; const targetCommandRegex = new RegExp( @@ -250,7 +250,7 @@ function processProject( ? `$1nx ${target} --configuration=${configuration}$3` : `$1nx ${target}$3` ); - replacedTargets.add(target); + hasChanges = true; } else { /** * Parse script and command to handle the following: @@ -327,7 +327,7 @@ function processProject( : `$1nx ${target}$4` ) ); - replacedTargets.add(target); + hasChanges = true; } else { // there are different args or the script has extra args, replace with the command leaving the args packageJson.scripts[scriptName] = packageJson.scripts[ @@ -341,14 +341,16 @@ function processProject( : `$1nx ${target}$3` ) ); - replacedTargets.add(target); + hasChanges = true; } } } } } - writeJson(tree, packageJsonPath, packageJson); + if (hasChanges) { + writeJson(tree, packageJsonPath, packageJson); + } } function getInferredTargetCommands(