diff --git a/packages/devkit/src/utils/add-plugin.spec.ts b/packages/devkit/src/utils/add-plugin.spec.ts index 70c8d547ea850..b70eb2e29efee 100644 --- a/packages/devkit/src/utils/add-plugin.spec.ts +++ b/packages/devkit/src/utils/add-plugin.spec.ts @@ -290,6 +290,55 @@ describe('addPlugin', () => { expect(scripts['build:dev']).toBe('nx build'); }); + it('should support replacing scripts where a command is the same as the cli entry point', async () => { + writeJson(tree, 'app1/package.json', { + name: 'app1', + scripts: { + dev: 'next', + build: 'tsc -b && next build', + preview: 'next preview', + }, + }); + + createNodes = [ + '**/next.config.{ts,js,cjs,mjs}', + () => [ + [ + 'app1/next.config.js', + { + projects: { + app1: { + name: 'app1', + targets: { + build: { command: 'next build' }, + dev: { command: 'next' }, + preview: { command: 'next preview' }, + }, + }, + }, + }, + ], + ], + ]; + + await addPlugin( + tree, + graph, + '@nx/next/plugin', + createNodes, + + { + targetName: ['build'], + }, + true + ); + + const { scripts } = readJson(tree, 'app1/package.json'); + expect(scripts.dev).toBe('nx dev'); + expect(scripts.build).toBe('tsc -b && nx build'); + expect(scripts.preview).toBe('nx preview'); + }); + it('should support replacing multiple scripts', async () => { writeJson(tree, 'app1/package.json', { name: 'app1', diff --git a/packages/devkit/src/utils/add-plugin.ts b/packages/devkit/src/utils/add-plugin.ts index e8fe33082f99d..965a0c4a44d13 100644 --- a/packages/devkit/src/utils/add-plugin.ts +++ b/packages/devkit/src/utils/add-plugin.ts @@ -232,6 +232,7 @@ function processProject( if (!tree.exists(packageJsonPath)) { return; } + const packageJson = readJson(tree, packageJsonPath); if (!packageJson.scripts || !Object.keys(packageJson.scripts).length) { return; @@ -243,6 +244,9 @@ function processProject( } let hasChanges = false; + targetCommands.sort( + (a, b) => b.command.split(/\s/).length - a.command.split(/\s/).length + ); for (const targetCommand of targetCommands) { const { command, target, configuration } = targetCommand; const targetCommandRegex = new RegExp( @@ -325,9 +329,8 @@ function processProject( if (!hasArgsWithDifferentValues && !scriptHasExtraArgs) { // they are the same, replace with the command removing the args - packageJson.scripts[scriptName] = packageJson.scripts[ - scriptName - ].replace( + const script = packageJson.scripts[scriptName]; + packageJson.scripts[scriptName] = script.replace( match, match.replace( commandRegex,