feat(core): remove deprecated defaultCollection and npmScope nx.json … (#19708)

This commit is contained in:
Jason Jean 2023-10-18 18:03:57 -04:00 committed by GitHub
parent d551351c51
commit d0005c954f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
61 changed files with 239 additions and 592 deletions

View File

@ -27,7 +27,6 @@ Nx.json configuration
- [implicitDependencies](../../devkit/documents/NxJsonConfiguration#implicitdependencies): ImplicitDependencyEntry<T> - [implicitDependencies](../../devkit/documents/NxJsonConfiguration#implicitdependencies): ImplicitDependencyEntry<T>
- [installation](../../devkit/documents/NxJsonConfiguration#installation): NxInstallationConfiguration - [installation](../../devkit/documents/NxJsonConfiguration#installation): NxInstallationConfiguration
- [namedInputs](../../devkit/documents/NxJsonConfiguration#namedinputs): Object - [namedInputs](../../devkit/documents/NxJsonConfiguration#namedinputs): Object
- [npmScope](../../devkit/documents/NxJsonConfiguration#npmscope): string
- [nxCloudAccessToken](../../devkit/documents/NxJsonConfiguration#nxcloudaccesstoken): string - [nxCloudAccessToken](../../devkit/documents/NxJsonConfiguration#nxcloudaccesstoken): string
- [nxCloudEncryptionKey](../../devkit/documents/NxJsonConfiguration#nxcloudencryptionkey): string - [nxCloudEncryptionKey](../../devkit/documents/NxJsonConfiguration#nxcloudencryptionkey): string
- [nxCloudUrl](../../devkit/documents/NxJsonConfiguration#nxcloudurl): string - [nxCloudUrl](../../devkit/documents/NxJsonConfiguration#nxcloudurl): string
@ -66,11 +65,10 @@ Default generator collection. It is used when no collection is provided.
#### Type declaration #### Type declaration
| Name | Type | Description | | Name | Type |
| :-------------------- | :-------------------------------------------------------- | :--------------------------------------------------------------------- | | :-------------------- | :-------------------------------------------------------- |
| `defaultCollection?` | `string` | **`Deprecated`** - defaultCollection is deprecated and will be removed | | `defaultProjectName?` | `string` |
| `defaultProjectName?` | `string` | - | | `packageManager?` | [`PackageManager`](../../devkit/documents/PackageManager) |
| `packageManager?` | [`PackageManager`](../../devkit/documents/PackageManager) | - |
--- ---
@ -151,17 +149,6 @@ Named inputs targets can refer to reduce duplication
--- ---
### npmScope
`Optional` **npmScope**: `string`
**`Deprecated`**
This is inferred from the package.json in the workspace root. Please use getNpmScope instead.
NPM Scope that the workspace uses
---
### nxCloudAccessToken ### nxCloudAccessToken
`Optional` **nxCloudAccessToken**: `string` `Optional` **nxCloudAccessToken**: `string`

View File

@ -86,7 +86,6 @@ It only uses language primitives and immutable objects
- [StringChange](../../devkit/documents/StringChange) - [StringChange](../../devkit/documents/StringChange)
- [TargetDefaults](../../devkit/documents/TargetDefaults) - [TargetDefaults](../../devkit/documents/TargetDefaults)
- [TaskGraphExecutor](../../devkit/documents/TaskGraphExecutor) - [TaskGraphExecutor](../../devkit/documents/TaskGraphExecutor)
- [WorkspaceConfiguration](../../devkit/documents/WorkspaceConfiguration)
- [WorkspaceJsonConfiguration](../../devkit/documents/WorkspaceJsonConfiguration) - [WorkspaceJsonConfiguration](../../devkit/documents/WorkspaceJsonConfiguration)
### Variables ### Variables
@ -118,11 +117,9 @@ It only uses language primitives and immutable objects
- [getPackageManagerVersion](../../devkit/documents/getPackageManagerVersion) - [getPackageManagerVersion](../../devkit/documents/getPackageManagerVersion)
- [getProjects](../../devkit/documents/getProjects) - [getProjects](../../devkit/documents/getProjects)
- [getWorkspaceLayout](../../devkit/documents/getWorkspaceLayout) - [getWorkspaceLayout](../../devkit/documents/getWorkspaceLayout)
- [getWorkspacePath](../../devkit/documents/getWorkspacePath)
- [glob](../../devkit/documents/glob) - [glob](../../devkit/documents/glob)
- [hashArray](../../devkit/documents/hashArray) - [hashArray](../../devkit/documents/hashArray)
- [installPackagesTask](../../devkit/documents/installPackagesTask) - [installPackagesTask](../../devkit/documents/installPackagesTask)
- [isStandaloneProject](../../devkit/documents/isStandaloneProject)
- [joinPathFragments](../../devkit/documents/joinPathFragments) - [joinPathFragments](../../devkit/documents/joinPathFragments)
- [moveFilesToNewDirectory](../../devkit/documents/moveFilesToNewDirectory) - [moveFilesToNewDirectory](../../devkit/documents/moveFilesToNewDirectory)
- [names](../../devkit/documents/names) - [names](../../devkit/documents/names)
@ -137,7 +134,6 @@ It only uses language primitives and immutable objects
- [readProjectConfiguration](../../devkit/documents/readProjectConfiguration) - [readProjectConfiguration](../../devkit/documents/readProjectConfiguration)
- [readProjectsConfigurationFromProjectGraph](../../devkit/documents/readProjectsConfigurationFromProjectGraph) - [readProjectsConfigurationFromProjectGraph](../../devkit/documents/readProjectsConfigurationFromProjectGraph)
- [readTargetOptions](../../devkit/documents/readTargetOptions) - [readTargetOptions](../../devkit/documents/readTargetOptions)
- [readWorkspaceConfiguration](../../devkit/documents/readWorkspaceConfiguration)
- [removeDependenciesFromPackageJson](../../devkit/documents/removeDependenciesFromPackageJson) - [removeDependenciesFromPackageJson](../../devkit/documents/removeDependenciesFromPackageJson)
- [removeProjectConfiguration](../../devkit/documents/removeProjectConfiguration) - [removeProjectConfiguration](../../devkit/documents/removeProjectConfiguration)
- [reverse](../../devkit/documents/reverse) - [reverse](../../devkit/documents/reverse)
@ -152,7 +148,6 @@ It only uses language primitives and immutable objects
- [updateNxJson](../../devkit/documents/updateNxJson) - [updateNxJson](../../devkit/documents/updateNxJson)
- [updateProjectConfiguration](../../devkit/documents/updateProjectConfiguration) - [updateProjectConfiguration](../../devkit/documents/updateProjectConfiguration)
- [updateTsConfigsToJs](../../devkit/documents/updateTsConfigsToJs) - [updateTsConfigsToJs](../../devkit/documents/updateTsConfigsToJs)
- [updateWorkspaceConfiguration](../../devkit/documents/updateWorkspaceConfiguration)
- [validateDependency](../../devkit/documents/validateDependency) - [validateDependency](../../devkit/documents/validateDependency)
- [visitNotIgnoredFiles](../../devkit/documents/visitNotIgnoredFiles) - [visitNotIgnoredFiles](../../devkit/documents/visitNotIgnoredFiles)
- [workspaceLayout](../../devkit/documents/workspaceLayout) - [workspaceLayout](../../devkit/documents/workspaceLayout)

View File

@ -25,7 +25,6 @@ use ProjectsConfigurations or NxJsonConfiguration
- [implicitDependencies](../../devkit/documents/Workspace#implicitdependencies): ImplicitDependencyEntry<string[] | "\*"> - [implicitDependencies](../../devkit/documents/Workspace#implicitdependencies): ImplicitDependencyEntry<string[] | "\*">
- [installation](../../devkit/documents/Workspace#installation): NxInstallationConfiguration - [installation](../../devkit/documents/Workspace#installation): NxInstallationConfiguration
- [namedInputs](../../devkit/documents/Workspace#namedinputs): Object - [namedInputs](../../devkit/documents/Workspace#namedinputs): Object
- [npmScope](../../devkit/documents/Workspace#npmscope): string
- [nxCloudAccessToken](../../devkit/documents/Workspace#nxcloudaccesstoken): string - [nxCloudAccessToken](../../devkit/documents/Workspace#nxcloudaccesstoken): string
- [nxCloudEncryptionKey](../../devkit/documents/Workspace#nxcloudencryptionkey): string - [nxCloudEncryptionKey](../../devkit/documents/Workspace#nxcloudencryptionkey): string
- [nxCloudUrl](../../devkit/documents/Workspace#nxcloudurl): string - [nxCloudUrl](../../devkit/documents/Workspace#nxcloudurl): string
@ -74,11 +73,10 @@ Default generator collection. It is used when no collection is provided.
#### Type declaration #### Type declaration
| Name | Type | Description | | Name | Type |
| :-------------------- | :-------------------------------------------------------- | :--------------------------------------------------------------------- | | :-------------------- | :-------------------------------------------------------- |
| `defaultCollection?` | `string` | **`Deprecated`** - defaultCollection is deprecated and will be removed | | `defaultProjectName?` | `string` |
| `defaultProjectName?` | `string` | - | | `packageManager?` | [`PackageManager`](../../devkit/documents/PackageManager) |
| `packageManager?` | [`PackageManager`](../../devkit/documents/PackageManager) | - |
#### Inherited from #### Inherited from
@ -187,21 +185,6 @@ Named inputs targets can refer to reduce duplication
--- ---
### npmScope
`Optional` **npmScope**: `string`
**`Deprecated`**
This is inferred from the package.json in the workspace root. Please use getNpmScope instead.
NPM Scope that the workspace uses
#### Inherited from
[NxJsonConfiguration](../../devkit/documents/NxJsonConfiguration).[npmScope](../../devkit/documents/NxJsonConfiguration#npmscope)
---
### nxCloudAccessToken ### nxCloudAccessToken
`Optional` **nxCloudAccessToken**: `string` `Optional` **nxCloudAccessToken**: `string`

View File

@ -1,7 +0,0 @@
# Type alias: WorkspaceConfiguration
Ƭ **WorkspaceConfiguration**: `Omit`<[`ProjectsConfigurations`](../../devkit/documents/ProjectsConfigurations), `"projects"`\> & `Partial`<[`NxJsonConfiguration`](../../devkit/documents/NxJsonConfiguration)\>
**`Deprecated`**
using NxJsonConfiguration

View File

@ -8,7 +8,7 @@ and the default scope.
Example: Example:
```typescript ```typescript
{ appsDir: 'apps', libsDir: 'libs', npmScope: 'myorg' } { appsDir: 'apps', libsDir: 'libs' }
``` ```
#### Parameters #### Parameters
@ -21,9 +21,8 @@ Example:
`Object` `Object`
| Name | Type | Description | | Name | Type |
| :-------------------- | :-------- | :----------------------------------------------------------------------- | | :-------------------- | :-------- |
| `appsDir` | `string` | - | | `appsDir` | `string` |
| `libsDir` | `string` | - | | `libsDir` | `string` |
| `npmScope` | `string` | **`Deprecated`** This will be removed in Nx 17. Use getNpmScope instead. | | `standaloneAsDefault` | `boolean` |
| `standaloneAsDefault` | `boolean` | - |

View File

@ -1,17 +0,0 @@
# Function: getWorkspacePath
**getWorkspacePath**(`tree`): `"angular.json"` \| `"workspace.json"`
#### Parameters
| Name | Type |
| :----- | :------------------------------------ |
| `tree` | [`Tree`](../../devkit/documents/Tree) |
#### Returns
`"angular.json"` \| `"workspace.json"`
**`Deprecated`**
all projects are configured using project.json

View File

@ -1,20 +0,0 @@
# Function: isStandaloneProject
**isStandaloneProject**(`tree`, `project`): `boolean`
Returns if a project has a standalone configuration (project.json).
#### Parameters
| Name | Type | Description |
| :-------- | :------------------------------------ | :------------------- |
| `tree` | [`Tree`](../../devkit/documents/Tree) | the file system tree |
| `project` | `string` | the project name |
#### Returns
`boolean`
**`Deprecated`**
non-standalone projects were deprecated

View File

@ -1,21 +0,0 @@
# Function: readWorkspaceConfiguration
**readWorkspaceConfiguration**(`tree`): [`WorkspaceConfiguration`](../../devkit/documents/WorkspaceConfiguration)
Read general workspace configuration such as the default project or cli settings
This does _not_ provide projects configuration, use [readProjectConfiguration](../../devkit/documents/readProjectConfiguration) instead.
#### Parameters
| Name | Type |
| :----- | :------------------------------------ |
| `tree` | [`Tree`](../../devkit/documents/Tree) |
#### Returns
[`WorkspaceConfiguration`](../../devkit/documents/WorkspaceConfiguration)
**`Deprecated`**
use readNxJson

View File

@ -1,22 +0,0 @@
# Function: updateWorkspaceConfiguration
**updateWorkspaceConfiguration**(`tree`, `workspaceConfig`): `void`
Update general workspace configuration such as the default project or cli settings.
This does _not_ update projects configuration, use [updateProjectConfiguration](../../devkit/documents/updateProjectConfiguration) or [addProjectConfiguration](../../devkit/documents/addProjectConfiguration) instead.
#### Parameters
| Name | Type |
| :---------------- | :------------------------------------------------------------------------ |
| `tree` | [`Tree`](../../devkit/documents/Tree) |
| `workspaceConfig` | [`WorkspaceConfiguration`](../../devkit/documents/WorkspaceConfiguration) |
#### Returns
`void`
**`Deprecated`**
use updateNxJson

View File

@ -9,11 +9,6 @@
"description": "Migrates an Angular CLI workspace to Nx or adds the Angular plugin to an Nx workspace. NOTE: Does not work in the `--dry-run` mode.", "description": "Migrates an Angular CLI workspace to Nx or adds the Angular plugin to an Nx workspace. NOTE: Does not work in the `--dry-run` mode.",
"type": "object", "type": "object",
"properties": { "properties": {
"npmScope": {
"type": "string",
"description": "Npm scope for importing libs. NOTE: only used if running the generator in an Angular CLI workspace.",
"x-deprecated": "This will be inferred from your root package.json"
},
"defaultBase": { "defaultBase": {
"type": "string", "type": "string",
"description": "Default base branch for affected. NOTE: only used if running the generator in an Angular CLI workspace.", "description": "Default base branch for affected. NOTE: only used if running the generator in an Angular CLI workspace.",

View File

@ -86,7 +86,6 @@ It only uses language primitives and immutable objects
- [StringChange](../../devkit/documents/StringChange) - [StringChange](../../devkit/documents/StringChange)
- [TargetDefaults](../../devkit/documents/TargetDefaults) - [TargetDefaults](../../devkit/documents/TargetDefaults)
- [TaskGraphExecutor](../../devkit/documents/TaskGraphExecutor) - [TaskGraphExecutor](../../devkit/documents/TaskGraphExecutor)
- [WorkspaceConfiguration](../../devkit/documents/WorkspaceConfiguration)
- [WorkspaceJsonConfiguration](../../devkit/documents/WorkspaceJsonConfiguration) - [WorkspaceJsonConfiguration](../../devkit/documents/WorkspaceJsonConfiguration)
### Variables ### Variables
@ -118,11 +117,9 @@ It only uses language primitives and immutable objects
- [getPackageManagerVersion](../../devkit/documents/getPackageManagerVersion) - [getPackageManagerVersion](../../devkit/documents/getPackageManagerVersion)
- [getProjects](../../devkit/documents/getProjects) - [getProjects](../../devkit/documents/getProjects)
- [getWorkspaceLayout](../../devkit/documents/getWorkspaceLayout) - [getWorkspaceLayout](../../devkit/documents/getWorkspaceLayout)
- [getWorkspacePath](../../devkit/documents/getWorkspacePath)
- [glob](../../devkit/documents/glob) - [glob](../../devkit/documents/glob)
- [hashArray](../../devkit/documents/hashArray) - [hashArray](../../devkit/documents/hashArray)
- [installPackagesTask](../../devkit/documents/installPackagesTask) - [installPackagesTask](../../devkit/documents/installPackagesTask)
- [isStandaloneProject](../../devkit/documents/isStandaloneProject)
- [joinPathFragments](../../devkit/documents/joinPathFragments) - [joinPathFragments](../../devkit/documents/joinPathFragments)
- [moveFilesToNewDirectory](../../devkit/documents/moveFilesToNewDirectory) - [moveFilesToNewDirectory](../../devkit/documents/moveFilesToNewDirectory)
- [names](../../devkit/documents/names) - [names](../../devkit/documents/names)
@ -137,7 +134,6 @@ It only uses language primitives and immutable objects
- [readProjectConfiguration](../../devkit/documents/readProjectConfiguration) - [readProjectConfiguration](../../devkit/documents/readProjectConfiguration)
- [readProjectsConfigurationFromProjectGraph](../../devkit/documents/readProjectsConfigurationFromProjectGraph) - [readProjectsConfigurationFromProjectGraph](../../devkit/documents/readProjectsConfigurationFromProjectGraph)
- [readTargetOptions](../../devkit/documents/readTargetOptions) - [readTargetOptions](../../devkit/documents/readTargetOptions)
- [readWorkspaceConfiguration](../../devkit/documents/readWorkspaceConfiguration)
- [removeDependenciesFromPackageJson](../../devkit/documents/removeDependenciesFromPackageJson) - [removeDependenciesFromPackageJson](../../devkit/documents/removeDependenciesFromPackageJson)
- [removeProjectConfiguration](../../devkit/documents/removeProjectConfiguration) - [removeProjectConfiguration](../../devkit/documents/removeProjectConfiguration)
- [reverse](../../devkit/documents/reverse) - [reverse](../../devkit/documents/reverse)
@ -152,7 +148,6 @@ It only uses language primitives and immutable objects
- [updateNxJson](../../devkit/documents/updateNxJson) - [updateNxJson](../../devkit/documents/updateNxJson)
- [updateProjectConfiguration](../../devkit/documents/updateProjectConfiguration) - [updateProjectConfiguration](../../devkit/documents/updateProjectConfiguration)
- [updateTsConfigsToJs](../../devkit/documents/updateTsConfigsToJs) - [updateTsConfigsToJs](../../devkit/documents/updateTsConfigsToJs)
- [updateWorkspaceConfiguration](../../devkit/documents/updateWorkspaceConfiguration)
- [validateDependency](../../devkit/documents/validateDependency) - [validateDependency](../../devkit/documents/validateDependency)
- [visitNotIgnoredFiles](../../devkit/documents/visitNotIgnoredFiles) - [visitNotIgnoredFiles](../../devkit/documents/visitNotIgnoredFiles)
- [workspaceLayout](../../devkit/documents/workspaceLayout) - [workspaceLayout](../../devkit/documents/workspaceLayout)

View File

@ -1,5 +1,9 @@
# defaultCollection # defaultCollection
{% callout type="caution" title="Experimental" %}
Configuring `defaultCollection` will no longer have any effect in Nx 17+
{% /callout %}
In the `nx.json` you can set a `defaultCollection` property like this: In the `nx.json` you can set a `defaultCollection` property like this:
```jsonc ```jsonc

View File

@ -53,7 +53,7 @@ The `npmScope` property of the `nx.json` file is deprecated as of version 16.2.0
In Nx 16, if the `npmScope` property is present, it will be used as a prefix. If the `npmScope` property is not present, the `name` property of the root `package.json` file will be used to infer the prefix. In Nx 16, if the `npmScope` property is present, it will be used as a prefix. If the `npmScope` property is not present, the `name` property of the root `package.json` file will be used to infer the prefix.
In Nx 17, the `npmScope` property will be ignored. In Nx 17, the `npmScope` property is ignored.
### Affected ### Affected

View File

@ -107,7 +107,7 @@ describe('convert Angular CLI workspace to an Nx workspace', () => {
expect(packageJson.devDependencies['@nx/workspace']).not.toBeDefined(); expect(packageJson.devDependencies['@nx/workspace']).not.toBeDefined();
// run ng add // run ng add
runCLI('g @nx/angular:ng-add --npm-scope projscope --default-base main'); runCLI('g @nx/angular:ng-add --default-base main');
// check that prettier config exits and that files have been moved // check that prettier config exits and that files have been moved
checkFilesExist( checkFilesExist(
@ -264,7 +264,7 @@ describe('convert Angular CLI workspace to an Nx workspace', () => {
it('should handle a workspace with cypress v9', () => { it('should handle a workspace with cypress v9', () => {
addCypress9(); addCypress9();
runCLI('g @nx/angular:ng-add --npm-scope projscope --skip-install'); runCLI('g @nx/angular:ng-add --skip-install');
const e2eProject = `${project}-e2e`; const e2eProject = `${project}-e2e`;
//check e2e project files //check e2e project files
@ -331,7 +331,7 @@ describe('convert Angular CLI workspace to an Nx workspace', () => {
it('should handle a workspace with cypress v10', () => { it('should handle a workspace with cypress v10', () => {
addCypress10(); addCypress10();
runCLI('g @nx/angular:ng-add --npm-scope projscope --skip-install'); runCLI('g @nx/angular:ng-add --skip-install');
const e2eProject = `${project}-e2e`; const e2eProject = `${project}-e2e`;
//check e2e project files //check e2e project files
@ -401,7 +401,7 @@ describe('convert Angular CLI workspace to an Nx workspace', () => {
it.skip('should handle a workspace with ESLint', () => { it.skip('should handle a workspace with ESLint', () => {
addEsLint(); addEsLint();
runCLI('g @nx/angular:ng-add --npm-scope projscope'); runCLI('g @nx/angular:ng-add');
checkFilesExist(`apps/${project}/.eslintrc.json`, `.eslintrc.json`); checkFilesExist(`apps/${project}/.eslintrc.json`, `.eslintrc.json`);
@ -438,7 +438,7 @@ describe('convert Angular CLI workspace to an Nx workspace', () => {
runCommand(`ng g @schematics/angular:application ${app1} --no-interactive`); runCommand(`ng g @schematics/angular:application ${app1} --no-interactive`);
runCommand(`ng g @schematics/angular:library ${lib1} --no-interactive`); runCommand(`ng g @schematics/angular:library ${lib1} --no-interactive`);
runCLI('g @nx/angular:ng-add --npm-scope projscope'); runCLI('g @nx/angular:ng-add');
// check angular.json does not exist // check angular.json does not exist
checkFilesDoNotExist('angular.json'); checkFilesDoNotExist('angular.json');

View File

@ -23,10 +23,10 @@ import {
import { join } from 'path'; import { join } from 'path';
describe('Nx Plugin', () => { describe('Nx Plugin', () => {
let npmScope: string; let workspaceName: string;
beforeAll(() => { beforeAll(() => {
npmScope = newProject(); workspaceName = newProject();
}); });
afterAll(() => cleanupProject()); afterAll(() => cleanupProject());
@ -292,7 +292,7 @@ describe('Nx Plugin', () => {
// Register plugin in nx.json (required for inference) // Register plugin in nx.json (required for inference)
updateFile(`nx.json`, (nxJson) => { updateFile(`nx.json`, (nxJson) => {
const nx = JSON.parse(nxJson); const nx = JSON.parse(nxJson);
nx.plugins = [`@${npmScope}/${plugin}`]; nx.plugins = [`@${workspaceName}/${plugin}`];
return JSON.stringify(nx, null, 2); return JSON.stringify(nx, null, 2);
}); });
@ -315,7 +315,7 @@ describe('Nx Plugin', () => {
const nx = JSON.parse(nxJson); const nx = JSON.parse(nxJson);
nx.plugins = [ nx.plugins = [
{ {
plugin: `@${npmScope}/${plugin}`, plugin: `@${workspaceName}/${plugin}`,
options: { inferredTags: ['my-tag'] }, options: { inferredTags: ['my-tag'] },
}, },
]; ];
@ -351,13 +351,13 @@ describe('Nx Plugin', () => {
); );
runCLI( runCLI(
`generate @${npmScope}/${plugin}:${generator} --name ${generatedProject}` `generate @${workspaceName}/${plugin}:${generator} --name ${generatedProject}`
); );
updateFile(`libs/${generatedProject}/project.json`, (f) => { updateFile(`libs/${generatedProject}/project.json`, (f) => {
const project: ProjectConfiguration = JSON.parse(f); const project: ProjectConfiguration = JSON.parse(f);
project.targets['execute'] = { project.targets['execute'] = {
executor: `@${npmScope}/${plugin}:${executor}`, executor: `@${workspaceName}/${plugin}:${executor}`,
}; };
return JSON.stringify(project, null, 2); return JSON.stringify(project, null, 2);
}); });
@ -383,7 +383,9 @@ describe('Nx Plugin', () => {
); );
runCLI( runCLI(
`generate @${npmScope}/${plugin}:${generator} --name ${uniq('test')}` `generate @${workspaceName}/${plugin}:${generator} --name ${uniq(
'test'
)}`
); );
}).not.toThrow(); }).not.toThrow();
updateFile('package.json', JSON.stringify(oldPackageJson, null, 2)); updateFile('package.json', JSON.stringify(oldPackageJson, null, 2));

View File

@ -213,13 +213,6 @@ describe('workspace', () => {
expect(tree.exists('angular.json')).toBe(false); expect(tree.exists('angular.json')).toBe(false);
}); });
it('should set the default collection to @nx/angular', async () => {
await migrateFromAngularCli(tree, {});
expect(
readJson(tree, 'nx.json').cli?.defaultCollection
).not.toBeDefined();
});
it('should set the default project correctly', async () => { it('should set the default project correctly', async () => {
await migrateFromAngularCli(tree, {}); await migrateFromAngularCli(tree, {});
expect(readJson(tree, 'nx.json').defaultProject).toBe('myApp'); expect(readJson(tree, 'nx.json').defaultProject).toBe('myApp');

View File

@ -3,10 +3,6 @@ import { E2eTestRunner, UnitTestRunner } from '../../utils/test-runners';
import type { Styles } from '../utils/types'; import type { Styles } from '../utils/types';
export interface GeneratorOptions { export interface GeneratorOptions {
/**
* @deprecated This should be inferred with {@link getNpmScope}
*/
npmScope?: string;
defaultBase?: string; defaultBase?: string;
unitTestRunner?: UnitTestRunner; unitTestRunner?: UnitTestRunner;

View File

@ -6,11 +6,6 @@
"description": "Migrates an Angular CLI workspace to Nx or adds the Angular plugin to an Nx workspace. NOTE: Does not work in the `--dry-run` mode.", "description": "Migrates an Angular CLI workspace to Nx or adds the Angular plugin to an Nx workspace. NOTE: Does not work in the `--dry-run` mode.",
"type": "object", "type": "object",
"properties": { "properties": {
"npmScope": {
"type": "string",
"description": "Npm scope for importing libs. NOTE: only used if running the generator in an Angular CLI workspace.",
"x-deprecated": "This will be inferred from your root package.json"
},
"defaultBase": { "defaultBase": {
"type": "string", "type": "string",
"description": "Default base branch for affected. NOTE: only used if running the generator in an Angular CLI workspace.", "description": "Default base branch for affected. NOTE: only used if running the generator in an Angular CLI workspace.",

View File

@ -11,7 +11,6 @@ const allowedProjectExtensions = [
const allowedWorkspaceExtensions = [ const allowedWorkspaceExtensions = [
'implicitDependencies', 'implicitDependencies',
'affected', 'affected',
'npmScope',
'tasksRunnerOptions', 'tasksRunnerOptions',
'workspaceLayout', 'workspaceLayout',
'plugins', 'plugins',

View File

@ -5,6 +5,7 @@ import { updateJson } from 'nx/src/generators/utils/json';
import { workspaceRoot } from 'nx/src/utils/workspace-root'; import { workspaceRoot } from 'nx/src/utils/workspace-root';
import { join } from 'path'; import { join } from 'path';
import { determineProjectNameAndRootOptions } from './project-name-and-root-utils'; import { determineProjectNameAndRootOptions } from './project-name-and-root-utils';
import { setCwd } from '../../internal-testing-utils';
describe('determineProjectNameAndRootOptions', () => { describe('determineProjectNameAndRootOptions', () => {
let tree: Tree; let tree: Tree;
@ -33,6 +34,9 @@ describe('determineProjectNameAndRootOptions', () => {
describe('no layout', () => { describe('no layout', () => {
beforeEach(() => { beforeEach(() => {
tree = createTreeWithEmptyWorkspace(); tree = createTreeWithEmptyWorkspace();
setCwd('');
jest.clearAllMocks(); jest.clearAllMocks();
}); });
@ -297,23 +301,6 @@ describe('determineProjectNameAndRootOptions', () => {
}); });
}); });
it('should derive import path for root projects when package.json does not have a name and format is as-provided', async () => {
updateJson(tree, 'package.json', (json) => {
json.name = undefined;
return json;
});
const result = await determineProjectNameAndRootOptions(tree, {
name: 'libName',
projectType: 'library',
projectNameAndRootFormat: 'as-provided',
rootProject: true,
callingGenerator: '',
});
expect(result.importPath).toBe('@proj/libName');
});
it('should throw when an invalid name is provided', async () => { it('should throw when an invalid name is provided', async () => {
await expect( await expect(
determineProjectNameAndRootOptions(tree, { determineProjectNameAndRootOptions(tree, {
@ -384,23 +371,6 @@ describe('determineProjectNameAndRootOptions', () => {
}); });
}); });
it('should derive import path for root projects when package.json does not have a name and format is "derived"', async () => {
updateJson(tree, 'package.json', (json) => {
json.name = undefined;
return json;
});
const result = await determineProjectNameAndRootOptions(tree, {
name: 'libName',
projectType: 'library',
projectNameAndRootFormat: 'derived',
rootProject: true,
callingGenerator: '',
});
expect(result.importPath).toBe('@proj/lib-name');
});
it(`should handle window's style paths correctly when format is "derived"`, async () => { it(`should handle window's style paths correctly when format is "derived"`, async () => {
const result = await determineProjectNameAndRootOptions(tree, { const result = await determineProjectNameAndRootOptions(tree, {
name: 'libName', name: 'libName',
@ -650,23 +620,6 @@ describe('determineProjectNameAndRootOptions', () => {
}); });
}); });
it('should derive import path for root projects when package.json does not have a name and format is "as-provided"', async () => {
updateJson(tree, 'package.json', (json) => {
json.name = undefined;
return json;
});
const result = await determineProjectNameAndRootOptions(tree, {
name: 'libName',
projectType: 'library',
projectNameAndRootFormat: 'as-provided',
rootProject: true,
callingGenerator: '',
});
expect(result.importPath).toBe('@proj/libName');
});
it('should throw when an invalid name is provided', async () => { it('should throw when an invalid name is provided', async () => {
await expect( await expect(
determineProjectNameAndRootOptions(tree, { determineProjectNameAndRootOptions(tree, {
@ -759,23 +712,6 @@ describe('determineProjectNameAndRootOptions', () => {
}); });
}); });
it('should derive import path for root projects when package.json does not have a name and format is "derived"', async () => {
updateJson(tree, 'package.json', (json) => {
json.name = undefined;
return json;
});
const result = await determineProjectNameAndRootOptions(tree, {
name: 'libName',
projectType: 'library',
projectNameAndRootFormat: 'derived',
rootProject: true,
callingGenerator: '',
});
expect(result.importPath).toBe('@proj/lib-name');
});
it('should prompt for the project name and root format', async () => { it('should prompt for the project name and root format', async () => {
// simulate interactive mode // simulate interactive mode
ensureInteractiveMode(); ensureInteractiveMode();

View File

@ -1,7 +1,7 @@
import { prompt } from 'enquirer'; import { prompt } from 'enquirer';
import type { ProjectType } from 'nx/src/config/workspace-json-project-json'; import type { ProjectType } from 'nx/src/config/workspace-json-project-json';
import type { Tree } from 'nx/src/generators/tree'; import type { Tree } from 'nx/src/generators/tree';
import { relative } from 'path'; import { join, relative } from 'path';
import { requireNx } from '../../nx'; import { requireNx } from '../../nx';
import { import {
extractLayoutDirectory, extractLayoutDirectory,
@ -14,8 +14,6 @@ const {
normalizePath, normalizePath,
logger, logger,
readJson, readJson,
readNxJson,
updateNxJson,
stripIndents, stripIndents,
workspaceRoot, workspaceRoot,
} = requireNx(); } = requireNx();
@ -329,13 +327,6 @@ function getImportPath(npmScope: string | undefined, name: string) {
} }
function getNpmScope(tree: Tree): string | undefined { function getNpmScope(tree: Tree): string | undefined {
const nxJson = readNxJson(tree);
// TODO(v17): Remove reading this from nx.json
if (nxJson?.npmScope) {
return nxJson.npmScope;
}
const { name } = tree.exists('package.json') const { name } = tree.exists('package.json')
? readJson<{ name?: string }>(tree, 'package.json') ? readJson<{ name?: string }>(tree, 'package.json')
: { name: null }; : { name: null };
@ -358,3 +349,10 @@ function getCwd(): string {
? process.env.INIT_CWD ? process.env.INIT_CWD
: process.cwd(); : process.cwd();
} }
/**
* Function for setting cwd during testing
*/
export function setCwd(path: string): void {
process.env.INIT_CWD = join(workspaceRoot, path);
}

View File

@ -10,7 +10,7 @@ const { readNxJson } = requireNx();
* Example: * Example:
* *
* ```typescript * ```typescript
* { appsDir: 'apps', libsDir: 'libs', npmScope: 'myorg' } * { appsDir: 'apps', libsDir: 'libs' }
* ``` * ```
* @param tree - file system tree * @param tree - file system tree
*/ */
@ -18,10 +18,6 @@ export function getWorkspaceLayout(tree: Tree): {
appsDir: string; appsDir: string;
libsDir: string; libsDir: string;
standaloneAsDefault: boolean; standaloneAsDefault: boolean;
/**
* @deprecated This will be removed in Nx 17. Use {@link getNpmScope} instead.
*/
npmScope: string;
} { } {
const nxJson = readNxJson(tree); const nxJson = readNxJson(tree);
return { return {
@ -31,7 +27,6 @@ export function getWorkspaceLayout(tree: Tree): {
libsDir: libsDir:
nxJson?.workspaceLayout?.libsDir ?? nxJson?.workspaceLayout?.libsDir ??
inOrderOfPreference(tree, ['libs', 'packages'], '.'), inOrderOfPreference(tree, ['libs', 'packages'], '.'),
npmScope: nxJson?.npmScope,
standaloneAsDefault: true, standaloneAsDefault: true,
}; };
} }

View File

@ -103,9 +103,7 @@ describe('Linter Builder', () => {
}, },
}, },
}, },
nxJsonConfiguration: { nxJsonConfiguration: {},
npmScope: 'test',
},
isVerbose: false, isVerbose: false,
}; };
mockLintFiles.mockImplementation(() => mockReports); mockLintFiles.mockImplementation(() => mockReports);

View File

@ -50,9 +50,7 @@ describe('Jest Executor', () => {
}, },
}, },
}, },
nxJsonConfiguration: { nxJsonConfiguration: {},
npmScope: 'test',
},
target: { target: {
executor: '@nx/jest:jest', executor: '@nx/jest:jest',
}, },

View File

@ -15,9 +15,7 @@ describe('tscExecutor', () => {
version: 2, version: 2,
projects: {}, projects: {},
}, },
nxJsonConfiguration: { nxJsonConfiguration: {},
npmScope: 'test',
},
isVerbose: false, isVerbose: false,
projectName: 'example', projectName: 'example',
targetName: 'build', targetName: 'build',

View File

@ -17,7 +17,7 @@ describe('setup-verdaccio generator', () => {
await generator(tree, options); await generator(tree, options);
const config = readJson(tree, 'project.json'); const config = readJson(tree, 'project.json');
expect(config).toEqual({ expect(config).toEqual({
name: 'test-name', name: '@proj/source',
$schema: 'node_modules/nx/schemas/project-schema.json', $schema: 'node_modules/nx/schemas/project-schema.json',
targets: { targets: {
'local-registry': { 'local-registry': {
@ -51,7 +51,7 @@ describe('setup-verdaccio generator', () => {
await generator(tree, options); await generator(tree, options);
const config = readJson(tree, 'project.json'); const config = readJson(tree, 'project.json');
expect(config).toEqual({ expect(config).toEqual({
name: 'test-name', name: '@proj/source',
$schema: 'node_modules/nx/schemas/project-schema.json', $schema: 'node_modules/nx/schemas/project-schema.json',
targets: { targets: {
'local-registry': { 'local-registry': {

View File

@ -1,16 +1,9 @@
import { Tree, readNxJson, readJson } from '@nx/devkit'; import { readJson, Tree } from '@nx/devkit';
/** /**
* Read the npm scope that a workspace should use by default * Read the npm scope that a workspace should use by default
*/ */
export function getNpmScope(tree: Tree): string | undefined { export function getNpmScope(tree: Tree): string | undefined {
const nxJson = readNxJson(tree);
// TODO(v17): Remove reading this from nx.json
if (nxJson?.npmScope) {
return nxJson.npmScope;
}
const { name } = tree.exists('package.json') const { name } = tree.exists('package.json')
? readJson<{ name?: string }>(tree, 'package.json') ? readJson<{ name?: string }>(tree, 'package.json')
: { name: null }; : { name: null };

View File

@ -16,6 +16,6 @@ exports[`init should add nuxt dependencies 1`] = `
"vue": "^3.3.4", "vue": "^3.3.4",
"vue-router": "^4.2.4", "vue-router": "^4.2.4",
}, },
"name": "test-name", "name": "@proj/source",
} }
`; `;

View File

@ -71,6 +71,11 @@
"version": "17.0.0-beta.3", "version": "17.0.0-beta.3",
"description": "Use minimal config for tasksRunnerOptions", "description": "Use minimal config for tasksRunnerOptions",
"implementation": "./src/migrations/update-17-0-0/use-minimal-config-for-tasks-runner-options" "implementation": "./src/migrations/update-17-0-0/use-minimal-config-for-tasks-runner-options"
},
"rm-default-collection-npm-scope": {
"version": "17.0.0-rc.1",
"description": "Migration for v17.0.0-rc.1",
"implementation": "./src/migrations/update-17-0-0/rm-default-collection-npm-scope"
} }
} }
} }

View File

@ -56,12 +56,6 @@ export function buildProjectConfigurationFromPackageJson(
} }
let name = packageJson.name ?? toProjectName(normalizedPath); let name = packageJson.name ?? toProjectName(normalizedPath);
if (nxJson?.npmScope) {
const npmPrefix = `@${nxJson.npmScope}/`;
if (name.startsWith(npmPrefix)) {
name = name.replace(npmPrefix, '');
}
}
const projectType = const projectType =
nxJson?.workspaceLayout?.appsDir != nxJson?.workspaceLayout?.libsDir && nxJson?.workspaceLayout?.appsDir != nxJson?.workspaceLayout?.libsDir &&
nxJson?.workspaceLayout?.appsDir && nxJson?.workspaceLayout?.appsDir &&

View File

@ -20,11 +20,6 @@
}, },
"additionalProperties": false "additionalProperties": false
}, },
"npmScope": {
"type": "string",
"description": "NPM Scope that the workspace uses.",
"deprecated": "This is inferred from the package.json in the workspace root instead."
},
"tasksRunnerOptions": { "tasksRunnerOptions": {
"type": "object", "type": "object",
"additionalProperties": { "additionalProperties": {
@ -221,10 +216,6 @@
"type": "string", "type": "string",
"description": "The default package manager to use.", "description": "The default package manager to use.",
"enum": ["yarn", "pnpm", "npm"] "enum": ["yarn", "pnpm", "npm"]
},
"defaultCollection": {
"type": "string",
"description": "The default generator collection to use."
} }
} }
}, },

View File

@ -53,7 +53,6 @@ export const allowedProjectExtensions = [
export const allowedWorkspaceExtensions = [ export const allowedWorkspaceExtensions = [
'implicitDependencies', 'implicitDependencies',
'affected', 'affected',
'npmScope',
'tasksRunnerOptions', 'tasksRunnerOptions',
'workspaceLayout', 'workspaceLayout',
'plugins', 'plugins',

View File

@ -22,8 +22,6 @@ import { workspaceRoot } from '../../utils/workspace-root';
import { NxJsonConfiguration } from '../../config/nx-json'; import { NxJsonConfiguration } from '../../config/nx-json';
import { calculateDefaultProjectName } from '../../config/calculate-default-project-name'; import { calculateDefaultProjectName } from '../../config/calculate-default-project-name';
import { findInstalledPlugins } from '../../utils/plugins/installed-plugins'; import { findInstalledPlugins } from '../../utils/plugins/installed-plugins';
import type { Arguments } from 'yargs';
import { output } from '../../utils/output';
import { getGeneratorInformation } from './generator-utils'; import { getGeneratorInformation } from './generator-utils';
export interface GenerateOptions { export interface GenerateOptions {
@ -204,7 +202,6 @@ export function parseGeneratorString(value: string): {
async function convertToGenerateOptions( async function convertToGenerateOptions(
generatorOptions: { [p: string]: any }, generatorOptions: { [p: string]: any },
defaultCollectionName: string,
mode: 'generate' | 'new', mode: 'generate' | 'new',
projectsConfiguration?: ProjectsConfigurations projectsConfiguration?: ProjectsConfigurations
): Promise<GenerateOptions> { ): Promise<GenerateOptions> {
@ -219,7 +216,7 @@ async function convertToGenerateOptions(
if (collection) { if (collection) {
collectionName = collection; collectionName = collection;
generatorName = generator; generatorName = generator;
} else if (!defaultCollectionName) { } else {
const generatorString = await promptForCollection( const generatorString = await promptForCollection(
generatorDescriptor, generatorDescriptor,
interactive, interactive,
@ -228,9 +225,6 @@ async function convertToGenerateOptions(
const parsedGeneratorString = parseGeneratorString(generatorString); const parsedGeneratorString = parseGeneratorString(generatorString);
collectionName = parsedGeneratorString.collection; collectionName = parsedGeneratorString.collection;
generatorName = parsedGeneratorString.generator; generatorName = parsedGeneratorString.generator;
} else {
collectionName = defaultCollectionName;
generatorName = generatorDescriptor;
} }
} else { } else {
collectionName = generatorOptions.collection as string; collectionName = generatorOptions.collection as string;
@ -270,11 +264,6 @@ function throwInvalidInvocation(availableGenerators: string[]) {
)})` )})`
); );
} }
function readDefaultCollection(nxConfig: NxJsonConfiguration) {
return nxConfig.cli ? nxConfig.cli.defaultCollection : null;
}
export function printGenHelp( export function printGenHelp(
opts: GenerateOptions, opts: GenerateOptions,
schema: Schema, schema: Schema,
@ -310,7 +299,6 @@ export async function generate(cwd: string, args: { [k: string]: any }) {
return handleErrors(verbose, async () => { return handleErrors(verbose, async () => {
const opts = await convertToGenerateOptions( const opts = await convertToGenerateOptions(
args, args,
readDefaultCollection(nxJsonConfiguration),
'generate', 'generate',
projectsConfigurations projectsConfigurations
); );

View File

@ -102,11 +102,6 @@ export interface NxJsonConfiguration<T = '*' | string[]> {
* Dependencies between different target names across all projects * Dependencies between different target names across all projects
*/ */
targetDefaults?: TargetDefaults; targetDefaults?: TargetDefaults;
/**
* @deprecated This is inferred from the package.json in the workspace root. Please use {@link getNpmScope} instead.
* NPM Scope that the workspace uses
*/
npmScope?: string;
/** /**
* Default options for `nx affected` * Default options for `nx affected`
*/ */
@ -158,10 +153,6 @@ export interface NxJsonConfiguration<T = '*' | string[]> {
cli?: { cli?: {
packageManager?: PackageManager; packageManager?: PackageManager;
/**
* @deprecated - defaultCollection is deprecated and will be removed
*/
defaultCollection?: string;
defaultProjectName?: string; defaultProjectName?: string;
}; };
/** /**

View File

@ -41,77 +41,6 @@ describe('Workspaces', () => {
fs.cleanup(); fs.cleanup();
}); });
describe('readWorkspaceConfiguration', () => {
it('should be able to inline project configurations', async () => {
const standaloneConfig = libConfig('lib1');
const config = {
version: 2,
projects: {
lib1: 'libs/lib1',
lib2: libConfig('lib2'),
},
};
await fs.createFiles({
'libs/lib1/project.json': JSON.stringify(standaloneConfig),
'libs/lib2/package.json': JSON.stringify({}),
'libs/domain/lib3/package.json': JSON.stringify({}),
'libs/domain/lib4/project.json': JSON.stringify({}),
'workspace.json': JSON.stringify(config),
});
const workspaces = new Workspaces(fs.tempDir);
const resolved = workspaces.readWorkspaceConfiguration();
expect(resolved.projects.lib1).toEqual(standaloneConfig);
});
it('should build project configurations from glob', async () => {
const lib1Config = libConfig('lib1');
const lib2Config = packageLibConfig('libs/lib2');
const domainPackageConfig = packageLibConfig(
'libs/domain/lib3',
'domain-lib3'
);
const domainLibConfig = libConfig('domain/lib4');
await fs.createFiles({
'libs/lib1/project.json': JSON.stringify(lib1Config),
'libs/lib1/package.json': JSON.stringify({ name: 'some-other-name' }),
'libs/lib2/package.json': JSON.stringify({ name: 'lib2' }),
'libs/domain/lib3/package.json': JSON.stringify({
name: 'domain-lib3',
}),
'libs/domain/lib4/project.json': JSON.stringify(domainLibConfig),
'libs/domain/lib4/package.json': JSON.stringify({}),
'package.json': JSON.stringify({
name: 'package-name',
workspaces: ['**/package.json'],
}),
});
const workspaces = new Workspaces(fs.tempDir);
const { projects } = workspaces.readWorkspaceConfiguration();
// projects got merged for lib1
expect(projects['lib1']).toEqual({
name: 'lib1',
root: 'libs/lib1',
sourceRoot: 'libs/lib1/src',
projectType: 'library',
targets: {
'nx-release-publish': {
dependsOn: ['^nx-release-publish'],
executor: '@nx/js:release-publish',
options: {},
},
},
});
expect(projects.lib2).toEqual(lib2Config);
expect(projects['domain-lib3']).toEqual(domainPackageConfig);
expect(projects['lib4']).toEqual(domainLibConfig);
});
});
describe('to project name', () => { describe('to project name', () => {
it('should lowercase names', () => { it('should lowercase names', () => {
const appResults = toProjectName('my-apps/directory/my-app/package.json'); const appResults = toProjectName('my-apps/directory/my-app/package.json');

View File

@ -123,17 +123,6 @@ export {
*/ */
export { glob } from './generators/utils/glob'; export { glob } from './generators/utils/glob';
/**
* @category Generators
*/
export {
readWorkspaceConfiguration,
updateWorkspaceConfiguration,
isStandaloneProject,
WorkspaceConfiguration,
getWorkspacePath,
} from './generators/utils/deprecated';
/** /**
* @category Generators * @category Generators
*/ */

View File

@ -25,7 +25,7 @@ function addCommonFiles(tree: Tree, addAppsAndLibsFolders: boolean): Tree {
tree.write( tree.write(
'/package.json', '/package.json',
JSON.stringify({ JSON.stringify({
name: 'test-name', name: '@proj/source',
dependencies: {}, dependencies: {},
devDependencies: {}, devDependencies: {},
}) })
@ -33,7 +33,6 @@ function addCommonFiles(tree: Tree, addAppsAndLibsFolders: boolean): Tree {
tree.write( tree.write(
'/nx.json', '/nx.json',
JSON.stringify({ JSON.stringify({
npmScope: 'proj',
affected: { affected: {
defaultBase: 'main', defaultBase: 'main',
}, },

View File

@ -1,110 +0,0 @@
import type { NxJsonConfiguration } from '../../config/nx-json';
import { ProjectsConfigurations } from '../../config/workspace-json-project-json';
import type { Tree } from '../tree';
import { readNxJson, updateNxJson } from './nx-json';
// TODO(v16): Remove this
/**
* @deprecated using NxJsonConfiguration
*/
export type WorkspaceConfiguration = Omit<ProjectsConfigurations, 'projects'> &
Partial<NxJsonConfiguration>;
// TODO(v16): Remove this
/**
* Update general workspace configuration such as the default project or cli settings.
*
* This does _not_ update projects configuration, use {@link updateProjectConfiguration} or {@link addProjectConfiguration} instead.
*
* @deprecated use updateNxJson
*/
export function updateWorkspaceConfiguration(
tree: Tree,
workspaceConfig: WorkspaceConfiguration
): void {
const {
// Nx Json Properties
affected,
cacheDirectory,
cli,
defaultProject,
extends: ext,
generators,
implicitDependencies,
installation,
namedInputs,
npmScope,
nxCloudAccessToken,
nxCloudEncryptionKey,
nxCloudUrl,
parallel,
plugins,
pluginsConfig,
release,
targetDefaults,
tasksRunnerOptions,
useDaemonProcess,
workspaceLayout,
} = workspaceConfig;
const nxJson: Required<NxJsonConfiguration> = {
affected,
cacheDirectory,
cli,
defaultProject,
extends: ext,
generators,
implicitDependencies,
installation,
namedInputs,
npmScope,
nxCloudAccessToken,
nxCloudEncryptionKey,
nxCloudUrl,
parallel,
plugins,
pluginsConfig,
release,
targetDefaults,
tasksRunnerOptions,
useDaemonProcess,
workspaceLayout,
};
updateNxJson(tree, nxJson);
}
// TODO(v16): Remove this
/**
* Returns if a project has a standalone configuration (project.json).
*
* @param tree - the file system tree
* @param project - the project name
*
* @deprecated non-standalone projects were deprecated
*/
export function isStandaloneProject(tree: Tree, project: string): boolean {
return true;
}
// TODO(v16): Remove this
/**
* Read general workspace configuration such as the default project or cli settings
*
* This does _not_ provide projects configuration, use {@link readProjectConfiguration} instead.
* @deprecated use readNxJson
*/
export function readWorkspaceConfiguration(tree: Tree): WorkspaceConfiguration {
return readNxJson(tree) as any;
}
// TODO(v16): Remove this
/**
* @deprecated all projects are configured using project.json
*/
export function getWorkspacePath(tree: Tree) {
if (tree.exists('workspace.json')) return 'workspace.json';
if (tree.exists('angular.json')) return 'angular.json';
return null;
}

View File

@ -26,13 +26,6 @@ import type { Tree } from '../tree';
import minimatch = require('minimatch'); import minimatch = require('minimatch');
export { readNxJson, updateNxJson } from './nx-json'; export { readNxJson, updateNxJson } from './nx-json';
export {
readWorkspaceConfiguration,
updateWorkspaceConfiguration,
isStandaloneProject,
getWorkspacePath,
WorkspaceConfiguration,
} from './deprecated';
/** /**
* Adds project configuration to the Nx workspace. * Adds project configuration to the Nx workspace.

View File

@ -0,0 +1,53 @@
import { createTree } from '../../generators/testing-utils/create-tree';
import update from './rm-default-collection-npm-scope';
import { readJson, updateJson, writeJson } from '../../generators/utils/json';
import { NxJsonConfiguration } from '../../config/nx-json';
import { Tree } from '../../generators/tree';
describe('rm-default-collection-npm-scope migration', () => {
let tree: Tree;
beforeEach(() => {
tree = createTree();
});
describe('with nx.json', () => {
beforeEach(() => {
writeJson(tree, 'nx.json', {
affected: {
defaultBase: 'master',
},
npmScope: 'scope',
cli: {
defaultCollection: 'collection',
},
} as NxJsonConfiguration & { npmScope: string; cli: { defaultCollection: string } });
});
it('should remove npmScope', async () => {
await update(tree);
expect(readJson(tree, 'nx.json').npmScope).not.toBeDefined();
});
it('should remove defaultCollection', async () => {
updateJson<NxJsonConfiguration>(tree, 'nx.json', (json) => {
json.cli.packageManager = 'npm';
return json;
});
await update(tree);
expect(readJson(tree, 'nx.json').cli).toEqual({
packageManager: 'npm',
});
});
it('should remove cli', async () => {
await update(tree);
expect(readJson(tree, 'nx.json').cli).not.toBeDefined();
});
});
describe('without nx.json', () => {
it('should run successfully', async () => {
await update(tree);
});
});
});

View File

@ -0,0 +1,96 @@
import { formatChangedFilesWithPrettierIfAvailable } from '../../generators/internal-utils/format-changed-files-with-prettier-if-available';
import { Tree } from '../../generators/tree';
import { readNxJson, updateNxJson } from '../../generators/utils/nx-json';
import { readJson } from '../../generators/utils/json';
import { logger } from '../../utils/logger';
import { NxJsonConfiguration } from '../../config/nx-json';
import { joinPathFragments } from '../../utils/path';
export default async function update(tree: Tree) {
if (!tree.exists('nx.json')) {
return;
}
const nxJson = readNxJson(tree);
delete nxJson.cli?.['defaultCollection'];
if (Object.keys(nxJson.cli).length < 1) {
delete nxJson.cli;
}
warnNpmScopeHasChanged(tree, nxJson);
delete nxJson['npmScope'];
updateNxJson(tree, nxJson);
await formatChangedFilesWithPrettierIfAvailable(tree);
}
function warnNpmScopeHasChanged(
tree: Tree,
nxJson: NxJsonConfiguration
): boolean {
const originalScope = nxJson['npmScope'];
// There was no original scope
if (!originalScope) {
return false;
}
// package.json does not exist
if (!tree.exists('package.json')) {
return false;
}
const newScope = getNpmScopeFromPackageJson(tree);
// New and Original scope are the same.
if (originalScope === newScope) {
return false;
}
const packageJsonName = readJson(tree, 'package.json').name;
if (newScope) {
logger.warn({
title: 'npmScope has been removed from nx.json',
bodyLines: [
'This will now be read from package.json',
`Old value which was in nx.json: ${originalScope}`,
`New value from package.json: ${newScope}`,
`Typescript path mappings for new libraries will now be generated as such: @${newScope}/new-lib instead of @${originalScope}/new-lib`,
`If you would like to change this back, change the name in package.json to ${packageJsonName.replace(
newScope,
originalScope
)}`,
],
});
} else {
// There is no scope in package.json
logger.warn({
title: 'npmScope has been removed from nx.json',
bodyLines: [
'This will now be read from package.json',
`Old value which was in nx.json: ${originalScope}`,
`New value from package.json: null`,
`Typescript path mappings for new libraries will now be generated as such: new-lib instead of @${originalScope}/new-lib`,
`If you would like to change this back, change the name in package.json to ${joinPathFragments(
`@${originalScope}`,
packageJsonName
)}`,
],
});
}
}
function getNpmScopeFromPackageJson(tree: Tree) {
const { name } = tree.exists('package.json')
? readJson<{ name?: string }>(tree, 'package.json')
: { name: null };
if (name?.startsWith('@')) {
return name.split('/')[0].substring(1);
}
}

View File

@ -16,9 +16,7 @@ describe('getTouchedNpmPackages', () => {
proj2: {}, proj2: {},
}, },
}; };
nxJson = { nxJson = {};
npmScope: 'scope',
};
projectGraph = { projectGraph = {
nodes: { nodes: {
proj1: { proj1: {

View File

@ -56,9 +56,7 @@ describe('getTouchedProjectsFromTsConfig', () => {
}, },
], ],
{}, {},
{ {}
npmScope: 'proj',
}
); );
expect(result).toEqual([]); expect(result).toEqual([]);
}); });

View File

@ -31,9 +31,7 @@ describe('explicit package json dependencies', () => {
}, },
}; };
const nxJsonConfiguration = { const nxJsonConfiguration = {};
npmScope: 'proj',
};
await tempFs.createFiles({ await tempFs.createFiles({
'./package.json': `{ './package.json': `{

View File

@ -25,9 +25,7 @@ export function buildExplicitPackageJsonDependencies(
Object.values(ctx.filesToProcess.projectFileMap[source]).forEach((f) => { Object.values(ctx.filesToProcess.projectFileMap[source]).forEach((f) => {
if (isPackageJsonAtProjectRoot(nodes, f.file)) { if (isPackageJsonAtProjectRoot(nodes, f.file)) {
// we only create the package name map once and only if a package.json file changes // we only create the package name map once and only if a package.json file changes
packageNameMap = packageNameMap = packageNameMap || createPackageNameMap(ctx.projects);
packageNameMap ||
createPackageNameMap(ctx.nxJsonConfiguration, ctx.projects);
processPackageJson(source, f.file, ctx, res, packageNameMap); processPackageJson(source, f.file, ctx, res, packageNameMap);
} }
}); });
@ -35,24 +33,14 @@ export function buildExplicitPackageJsonDependencies(
return res; return res;
} }
function createPackageNameMap( function createPackageNameMap(projects: ProjectsConfigurations['projects']) {
nxJsonConfiguration: NxJsonConfiguration,
projects: ProjectsConfigurations['projects']
) {
const res = {}; const res = {};
for (let projectName of Object.keys(projects)) { for (let projectName of Object.keys(projects)) {
try { try {
const packageJson = parseJson( const packageJson = parseJson(
defaultFileRead(join(projects[projectName].root, 'package.json')) defaultFileRead(join(projects[projectName].root, 'package.json'))
); );
// TODO(v17): Stop reading nx.json for the npmScope res[packageJson.name ?? projectName] = projectName;
const npmScope = nxJsonConfiguration.npmScope;
res[
packageJson.name ??
(npmScope
? `${npmScope === '@' ? '' : '@'}${npmScope}/${projectName}`
: projectName)
] = projectName;
} catch (e) {} } catch (e) {}
} }
return res; return res;

View File

@ -476,9 +476,7 @@ interface VirtualWorkspaceConfig {
async function createContext( async function createContext(
config: VirtualWorkspaceConfig config: VirtualWorkspaceConfig
): Promise<CreateDependenciesContext> { ): Promise<CreateDependenciesContext> {
const nxJson = { const nxJson = {};
npmScope: 'proj',
};
const projectsFs = { const projectsFs = {
[`./libs/${config.source}/project.json`]: JSON.stringify({ [`./libs/${config.source}/project.json`]: JSON.stringify({
name: config.source, name: config.source,

View File

@ -13,9 +13,7 @@ describe('getTouchedProjectsInWorkspaceJson', () => {
}, },
], ],
{}, {},
{ {}
npmScope: 'proj',
}
); );
expect(result).toEqual([]); expect(result).toEqual([]);
}); });

View File

@ -346,7 +346,6 @@ describe('nx deps utils', () => {
function createNxJson(p: Partial<NxJsonConfiguration>): NxJsonConfiguration { function createNxJson(p: Partial<NxJsonConfiguration>): NxJsonConfiguration {
const defaults: NxJsonConfiguration = { const defaults: NxJsonConfiguration = {
npmScope: '',
workspaceLayout: {} as any, workspaceLayout: {} as any,
plugins: ['plugin'], plugins: ['plugin'],
}; };

View File

@ -10,9 +10,7 @@ describe('getRunner', () => {
let overrides: any; let overrides: any;
beforeEach(() => { beforeEach(() => {
nxJson = { nxJson = {};
npmScope: 'proj',
};
mockRunner = jest.fn(); mockRunner = jest.fn();
}); });

View File

@ -4,6 +4,7 @@ import {
readJson, readJson,
readProjectConfiguration, readProjectConfiguration,
Tree, Tree,
updateJson,
} from '@nx/devkit'; } from '@nx/devkit';
import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing'; import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';
import { Linter } from '@nx/eslint'; import { Linter } from '@nx/eslint';
@ -242,10 +243,10 @@ describe('NxPlugin Plugin Generator', () => {
}); });
it('should correctly setup npmScope less workspaces', async () => { it('should correctly setup npmScope less workspaces', async () => {
// remove the npmScope from nx.json updateJson(tree, 'package.json', (j) => {
const nxJson = JSON.parse(tree.read('nx.json')!.toString()); j.name = 'source';
delete nxJson.npmScope; return j;
tree.write('nx.json', JSON.stringify(nxJson)); });
await pluginGenerator(tree, getSchema()); await pluginGenerator(tree, getSchema());

View File

@ -19,6 +19,5 @@ describe('preset generator', () => {
expect(config).toBeDefined(); expect(config).toBeDefined();
const packageJson = readJson<PackageJson>(tree, 'package.json'); const packageJson = readJson<PackageJson>(tree, 'package.json');
expect(packageJson.dependencies).toHaveProperty('@nx/devkit'); expect(packageJson.dependencies).toHaveProperty('@nx/devkit');
expect(readJson(tree, 'nx.json').npmScope).not.toBeDefined();
}); });
}); });

View File

@ -1,12 +1,10 @@
import { import {
Tree,
updateJson,
updateNxJson,
readNxJson,
formatFiles, formatFiles,
runTasksInSerial,
GeneratorCallback, GeneratorCallback,
names, names,
runTasksInSerial,
Tree,
updateJson,
} from '@nx/devkit'; } from '@nx/devkit';
import { Linter } from '@nx/eslint'; import { Linter } from '@nx/eslint';
import { PackageJson } from 'nx/src/utils/package-json'; import { PackageJson } from 'nx/src/utils/package-json';
@ -43,7 +41,6 @@ export default async function (tree: Tree, options: PresetGeneratorSchema) {
}); });
tasks.push(pluginTask); tasks.push(pluginTask);
removeNpmScope(tree);
moveNxPluginToDevDeps(tree); moveNxPluginToDevDeps(tree);
if (options.createPackageName) { if (options.createPackageName) {
@ -65,11 +62,6 @@ export default async function (tree: Tree, options: PresetGeneratorSchema) {
return runTasksInSerial(...tasks); return runTasksInSerial(...tasks);
} }
function removeNpmScope(tree: Tree) {
updateNxJson(tree, { ...readNxJson(tree), npmScope: undefined });
}
function moveNxPluginToDevDeps(tree: Tree) { function moveNxPluginToDevDeps(tree: Tree) {
updateJson<PackageJson>(tree, 'package.json', (json) => { updateJson<PackageJson>(tree, 'package.json', (json) => {
const nxPluginEntry = json.dependencies['@nx/plugin']; const nxPluginEntry = json.dependencies['@nx/plugin'];

View File

@ -18,9 +18,7 @@ describe('rollupExecutor', () => {
version: 2, version: 2,
projects: {}, projects: {},
}, },
nxJsonConfiguration: { nxJsonConfiguration: {},
npmScope: 'test',
},
isVerbose: false, isVerbose: false,
projectName: 'example', projectName: 'example',
targetName: 'build', targetName: 'build',

View File

@ -20,6 +20,6 @@ exports[`@nx/storybook:init dependencies for package.json should add angular rel
"prettier": "^2.6.2", "prettier": "^2.6.2",
"typescript": "~5.1.3", "typescript": "~5.1.3",
}, },
"name": "test-name", "name": "@proj/source",
} }
`; `;

View File

@ -103,7 +103,6 @@ exports[`Ignore @nx/react/plugins/storybook in Storybook eslint plugin should up
"!{projectRoot}/tsconfig.storybook.json", "!{projectRoot}/tsconfig.storybook.json",
], ],
}, },
"npmScope": "proj",
"targetDefaults": { "targetDefaults": {
"build": { "build": {
"cache": true, "cache": true,

View File

@ -18,7 +18,7 @@ exports[`@nx/vite:init dependencies for package.json should add vite packages an
"vite": "~4.3.9", "vite": "~4.3.9",
"vitest": "~0.32.0", "vitest": "~0.32.0",
}, },
"name": "test-name", "name": "@proj/source",
} }
`; `;
@ -37,7 +37,7 @@ exports[`@nx/vite:init dependencies for package.json should support --testEnviro
"vite": "~4.3.9", "vite": "~4.3.9",
"vitest": "~0.32.0", "vitest": "~0.32.0",
}, },
"name": "test-name", "name": "@proj/source",
} }
`; `;
@ -56,7 +56,7 @@ exports[`@nx/vite:init dependencies for package.json should support --testEnviro
"vite": "~4.3.9", "vite": "~4.3.9",
"vitest": "~0.32.0", "vitest": "~0.32.0",
}, },
"name": "test-name", "name": "@proj/source",
} }
`; `;
@ -75,6 +75,6 @@ exports[`@nx/vite:init dependencies for package.json should support --testEnviro
"vite": "~4.3.9", "vite": "~4.3.9",
"vitest": "~0.32.0", "vitest": "~0.32.0",
}, },
"name": "test-name", "name": "@proj/source",
} }
`; `;

View File

@ -18,6 +18,6 @@ exports[`init should add vue dependencies 1`] = `
"prettier": "^2.6.2", "prettier": "^2.6.2",
"typescript": "~5.1.3", "typescript": "~5.1.3",
}, },
"name": "test-name", "name": "@proj/source",
} }
`; `;

View File

@ -66,7 +66,7 @@ exports[`lib should add correct jest.config.ts and dependencies to package.json
"ts-node": "10.9.1", "ts-node": "10.9.1",
"typescript": "~5.1.3", "typescript": "~5.1.3",
}, },
"name": "test-name", "name": "@proj/source",
} }
`; `;
@ -262,7 +262,7 @@ exports[`lib should add vue, vite and vitest to package.json 1`] = `
"vite": "~4.3.9", "vite": "~4.3.9",
"vitest": "~0.32.0", "vitest": "~0.32.0",
}, },
"name": "test-name", "name": "@proj/source",
} }
`; `;

View File

@ -27,6 +27,7 @@ import { join } from 'path';
import { nxVersion, swcLoaderVersion } from '../../utils/versions'; import { nxVersion, swcLoaderVersion } from '../../utils/versions';
import { webInitGenerator } from '../init/init'; import { webInitGenerator } from '../init/init';
import { Schema } from './schema'; import { Schema } from './schema';
import { getNpmScope } from '@nx/js/src/utils/package-json/get-npm-scope';
interface NormalizedSchema extends Schema { interface NormalizedSchema extends Schema {
projectName: string; projectName: string;
@ -384,7 +385,7 @@ async function normalizeOptions(
const e2eProjectName = `${appProjectName}-e2e`; const e2eProjectName = `${appProjectName}-e2e`;
const e2eProjectRoot = `${appProjectRoot}-e2e`; const e2eProjectRoot = `${appProjectRoot}-e2e`;
const { npmScope } = getWorkspaceLayout(host); const npmScope = getNpmScope(host);
const parsedTags = options.tags const parsedTags = options.tags
? options.tags.split(',').map((s) => s.trim()) ? options.tags.split(',').map((s) => s.trim())

View File

@ -22,6 +22,7 @@ import { moveGenerator } from '../../generators/move/move';
import { nxVersion } from '../../utils/versions'; import { nxVersion } from '../../utils/versions';
import { PackageJson } from 'nx/src/utils/package-json'; import { PackageJson } from 'nx/src/utils/package-json';
import { posix } from 'path'; import { posix } from 'path';
import { getNpmScope } from '../../utilities/get-import-path';
const PROJECT_NAME = 'workspace-plugin'; const PROJECT_NAME = 'workspace-plugin';
const DESTINATION = `tools/${PROJECT_NAME}`; const DESTINATION = `tools/${PROJECT_NAME}`;
@ -170,7 +171,7 @@ async function createNewPlugin(tree: Tree) {
// nx-ignore-next-line // nx-ignore-next-line
const { Linter } = ensurePackage('@nx/eslint', nxVersion); const { Linter } = ensurePackage('@nx/eslint', nxVersion);
const { npmScope } = getWorkspaceLayout(tree); const npmScope = getNpmScope(tree);
const importPath = npmScope ? `@${npmScope}/${PROJECT_NAME}` : PROJECT_NAME; const importPath = npmScope ? `@${npmScope}/${PROJECT_NAME}` : PROJECT_NAME;
await pluginGenerator(tree, { await pluginGenerator(tree, {

View File

@ -1,5 +1,4 @@
import { Tree } from 'nx/src/generators/tree'; import { Tree } from 'nx/src/generators/tree';
import { readNxJson } from 'nx/src/generators/utils/nx-json';
import { readJson } from 'nx/src/generators/utils/json'; import { readJson } from 'nx/src/generators/utils/json';
export function getImportPath(tree: Tree, projectDirectory: string): string { export function getImportPath(tree: Tree, projectDirectory: string): string {
@ -10,13 +9,6 @@ export function getImportPath(tree: Tree, projectDirectory: string): string {
} }
export function getNpmScope(tree: Tree) { export function getNpmScope(tree: Tree) {
const nxJson = readNxJson(tree);
// TODO(v17): Remove reading this from nx.json
if (nxJson.npmScope) {
return nxJson.npmScope;
}
const { name } = tree.exists('package.json') const { name } = tree.exists('package.json')
? readJson<{ name?: string }>(tree, 'package.json') ? readJson<{ name?: string }>(tree, 'package.json')
: { name: null }; : { name: null };