Skip to content

Commit

Permalink
fix(misc): do not add includedScripts unless really needed when runni…
Browse files Browse the repository at this point in the history
…ng nx add (#22180)

(cherry picked from commit 1731ad8)
  • Loading branch information
leosvelperez authored and FrozenPandaz committed Mar 8, 2024
1 parent 4698b24 commit d3b9b21
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 4 deletions.
35 changes: 35 additions & 0 deletions packages/devkit/src/utils/update-package-scripts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,41 @@ describe('updatePackageScripts', () => {
]);
});

it('should not set "nx.includedScripts" when no script matched an inferred target', async () => {
tree.write('vite.config.ts', '');
writeJson(tree, 'package.json', {
name: 'app1',
scripts: {
serve: 'vite',
coverage: 'vitest run --coverage',
foo: 'echo "foo"',
},
});

await updatePackageScripts(tree, [
'**/{vite,vitest}.config.{js,ts,mjs,mts,cjs,cts}',
() => ({
projects: {
app1: {
targets: {
build: { command: 'vite build' },
serve: { command: 'vite serve' },
test: { command: 'vitest run' },
},
},
},
}),
]);

const packageJson = readJson<PackageJson>(tree, 'package.json');
expect(packageJson.scripts).toStrictEqual({
serve: 'vite',
coverage: 'nx test --coverage',
foo: 'echo "foo"',
});
expect(packageJson.nx).toBeUndefined();
});

it('should exclude replaced package.json scripts from nx if they are initially included', async () => {
tree.write('next.config.js', '');
writeJson(tree, 'package.json', {
Expand Down
13 changes: 9 additions & 4 deletions packages/devkit/src/utils/update-package-scripts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,20 +175,25 @@ async function processProject(
}
}

packageJson.nx ??= {};
if (process.env.NX_RUNNING_NX_INIT === 'true') {
// running `nx init` so we want to exclude everything by default
packageJson.nx ??= {};
packageJson.nx.includedScripts = [];
} else {
} else if (replacedTargets.size) {
/**
* Running `nx add`. In this case we want to:
* - if `includedScripts` is already set: exclude scripts that match inferred targets that were used to replace a script
* - if `includedScripts` is not set: set `includedScripts` with all scripts except the ones that match an inferred target that was used to replace a script
*/
packageJson.nx.includedScripts ??= Object.keys(packageJson.scripts);
packageJson.nx.includedScripts = packageJson.nx.includedScripts.filter(
const includedScripts =
packageJson.nx?.includedScripts ?? Object.keys(packageJson.scripts);
const filteredScripts = includedScripts.filter(
(s) => !replacedTargets.has(s)
);
if (filteredScripts.length !== includedScripts.length) {
packageJson.nx ??= {};
packageJson.nx.includedScripts = filteredScripts;
}
}

writeJson(tree, packageJsonPath, packageJson);
Expand Down

0 comments on commit d3b9b21

Please sign in to comment.