Skip to content

Commit

Permalink
cleanup(angular): replace wrapAngularDevkitSchematics for component (#…
Browse files Browse the repository at this point in the history
Coly010 authored Mar 22, 2023
1 parent 7cb3a3f commit 4dbe6a5
Showing 13 changed files with 215 additions and 104 deletions.
5 changes: 5 additions & 0 deletions docs/generated/packages/angular/generators/component.json
Original file line number Diff line number Diff line change
@@ -28,6 +28,11 @@
"$default": { "$source": "argv", "index": 0 },
"x-prompt": "What name would you like to use for the component?"
},
"prefix": {
"type": "string",
"description": "The prefix to apply to the generated component selector.",
"alias": "p"
},
"displayBlock": {
"description": "Specifies if the style will contain `:host { display: block; }`.",
"type": "boolean",
Original file line number Diff line number Diff line change
@@ -4,55 +4,47 @@ exports[`component Generator --flat should create the component correctly and ex
"import { Component } from '@angular/core';
@Component({
selector: 'example',
selector: 'proj-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
}
export class ExampleComponent {}
"
`;

exports[`component Generator --flat should create the component correctly and not export it when "export=false" 1`] = `
"import { Component } from '@angular/core';
@Component({
selector: 'example',
selector: 'proj-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
}
export class ExampleComponent {}
"
`;

exports[`component Generator --path should create the component correctly and export it in the entry point 1`] = `
"import { Component } from '@angular/core';
@Component({
selector: 'example',
selector: 'proj-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
}
export class ExampleComponent {}
"
`;

exports[`component Generator secondary entry points should create the component correctly and export it in the entry point 1`] = `
"import { Component } from '@angular/core';
@Component({
selector: 'example',
selector: 'proj-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
}
export class ExampleComponent {}
"
`;

@@ -65,13 +57,11 @@ exports[`component Generator should create the component correctly and export it
"import { Component } from '@angular/core';
@Component({
selector: 'example',
selector: 'proj-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
}
export class ExampleComponent {}
"
`;

@@ -85,29 +75,25 @@ exports[`component Generator should create the component correctly and export it
import { CommonModule } from '@angular/common';
@Component({
selector: 'example',
selector: 'proj-example',
standalone: true,
imports: [CommonModule],
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
}
export class ExampleComponent {}
"
`;

exports[`component Generator should create the component correctly and not export it in the entry point when "export=false" 1`] = `
"import { Component } from '@angular/core';
@Component({
selector: 'example',
selector: 'proj-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
}
export class ExampleComponent {}
"
`;

@@ -116,42 +102,36 @@ exports[`component Generator should create the component correctly and not expor
import { CommonModule } from '@angular/common';
@Component({
selector: 'example',
selector: 'proj-example',
standalone: true,
imports: [CommonModule],
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
}
export class ExampleComponent {}
"
`;

exports[`component Generator should create the component correctly and not export it when "--skip-import=true" 1`] = `
"import { Component } from '@angular/core';
@Component({
selector: 'example',
selector: 'proj-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
}
export class ExampleComponent {}
"
`;

exports[`component Generator should create the component correctly but not export it in the entry point when it does not exist 1`] = `
"import { Component } from '@angular/core';
@Component({
selector: 'example',
selector: 'proj-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
}
export class ExampleComponent {}
"
`;
110 changes: 102 additions & 8 deletions packages/angular/src/generators/component/component.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import type { Tree } from '@nrwl/devkit';
import { formatFiles, stripIndents } from '@nrwl/devkit';
import {
formatFiles,
generateFiles,
joinPathFragments,
names,
readNxJson,
stripIndents,
} from '@nrwl/devkit';
import { lt } from 'semver';
import { checkPathUnderProjectRoot } from '../utils/path';
import { getInstalledAngularVersionInfo } from '../utils/version-utils';
import { exportComponentInEntryPoint } from './lib/component';
import { normalizeOptions } from './lib/normalize-options';
import type { Schema } from './schema';
import { addToNgModule } from '../utils';
import { findModuleFromOptions } from './lib/module';

export async function componentGenerator(tree: Tree, rawOptions: Schema) {
const installedAngularVersionInfo = getInstalledAngularVersionInfo(tree);
@@ -19,20 +28,105 @@ export async function componentGenerator(tree: Tree, rawOptions: Schema) {
}

const options = await normalizeOptions(tree, rawOptions);
const { projectSourceRoot, ...schematicOptions } = options;

checkPathUnderProjectRoot(tree, options.project, options.path);

const { wrapAngularDevkitSchematic } = require('@nrwl/devkit/ngcli-adapter');
const angularComponentSchematic = wrapAngularDevkitSchematic(
'@schematics/angular',
'component'
);
await angularComponentSchematic(tree, schematicOptions);
const pathToGenerate = options.flat
? joinPathFragments(__dirname, './files/__fileName__')
: joinPathFragments(__dirname, './files');

const componentNames = names(options.name);
const typeNames = names(options.type);

const selector =
options.selector ||
buildSelector(tree, componentNames.fileName, options.prefix);

generateFiles(tree, pathToGenerate, options.path, {
fileName: componentNames.fileName,
className: componentNames.className,
type: typeNames.fileName,
typeClassName: typeNames.className,
style: options.style,
inlineStyle: options.inlineStyle,
inlineTemplate: options.inlineTemplate,
standalone: options.standalone,
skipSelector: options.skipSelector,
changeDetection: options.changeDetection,
viewEncapsulation: options.viewEncapsulation,
displayBlock: options.displayBlock,
selector,
tpl: '',
});

if (options.skipTests) {
const pathToSpecFile = joinPathFragments(
options.path,
`${!options.flat ? `${componentNames.fileName}/` : ``}${
componentNames.fileName
}.${typeNames.fileName}.spec.ts`
);

tree.delete(pathToSpecFile);
}

if (options.inlineTemplate) {
const pathToTemplateFile = joinPathFragments(
options.path,
`${!options.flat ? `${componentNames.fileName}/` : ``}${
componentNames.fileName
}.${typeNames.fileName}.html`
);

tree.delete(pathToTemplateFile);
}

if (options.inlineStyle) {
const pathToStyleFile = joinPathFragments(
options.path,
`${!options.flat ? `${componentNames.fileName}/` : ``}${
componentNames.fileName
}.${typeNames.fileName}.${options.style}`
);

tree.delete(pathToStyleFile);
}

if (!options.skipImport && !options.standalone) {
const modulePath = findModuleFromOptions(
tree,
options,
options.projectRoot
);
addToNgModule(
tree,
options.path,
modulePath,
componentNames.fileName,
`${componentNames.className}${typeNames.className}`,
options.flat
? `${componentNames.fileName}.${typeNames.fileName}`
: joinPathFragments(
componentNames.fileName,
`${componentNames.fileName}.${typeNames.fileName}`
),
'declarations',
options.flat,
options.export
);
}

exportComponentInEntryPoint(tree, options);

await formatFiles(tree);
}

function buildSelector(tree: Tree, name: string, prefix: string) {
const selectorPrefix = names(
prefix ?? readNxJson(tree).npmScope ?? 'app'
).fileName;

return names(`${selectorPrefix}-${name}`).fileName;
}

export default componentGenerator;
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<% if(displayBlock){ if(style != 'sass') { %>:host {
display: block;
}
<% } else { %>\:host
display: block;
<% }} %>
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p><%= fileName %> works!</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { <%= className %><%= typeClassName %> } from './<%= fileName %><%= type ? '.' + type: '' %>';

describe('<%= className %><%= typeClassName %>', () => {
let component: <%= className %><%= typeClassName %>;
let fixture: ComponentFixture<<%= className %><%= typeClassName %>>;

beforeEach(async () => {
await TestBed.configureTestingModule({
<%= standalone ? 'imports' : 'declarations' %>: [ <%= className %><%= typeClassName %> ]
})
.compileComponents();

fixture = TestBed.createComponent(<%= className %><%= typeClassName %>);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { <% if(changeDetection !== 'Default') { %>ChangeDetectionStrategy, <% }%>Component<% if(!!viewEncapsulation) { %>, ViewEncapsulation<% }%> } from '@angular/core';<% if(standalone) {%>
import { CommonModule } from '@angular/common';<% } %>

@Component({<% if(!skipSelector) {%>
selector: '<%= selector %>',<%}%><% if(standalone) {%>
standalone: true,
imports: [CommonModule],<%}%><% if(inlineTemplate) { %>
template: `<p><%= fileName %> works!</p>`<% } else { %>
templateUrl: './<%= fileName %><%= type ? '.' + type : '' %>.html'<% } if(inlineStyle) { %>,
styles: [<% if(displayBlock){ %>
`
:host {
display: block;
}
`<% } %>
]<% } else if (style !== 'none') { %>,
styleUrls: ['./<%= fileName %><%= type ? '.' + type : '' %>.<%= style %>']<% } %><% if(!!viewEncapsulation) { %>,
encapsulation: ViewEncapsulation.<%= viewEncapsulation %><% } if (changeDetection !== 'Default') { %>,
changeDetection: ChangeDetectionStrategy.<%= changeDetection %><% } %>
})
export class <%= className %><%= typeClassName %> {}
2 changes: 1 addition & 1 deletion packages/angular/src/generators/component/lib/component.ts
Original file line number Diff line number Diff line change
@@ -11,7 +11,7 @@ export function exportComponentInEntryPoint(
tree: Tree,
schema: NormalizedSchema
): void {
if (!schema.export || (schema.skipImport && !schema.standalone)) {
if (!schema.export || schema.skipImport) {
return;
}

Original file line number Diff line number Diff line change
@@ -11,16 +11,27 @@ export async function normalizeOptions(
options.project
);
const projectSourceRoot = sourceRoot ?? joinPathFragments(root, 'src');

const parsedName = options.name.split('/');
const name = parsedName.pop();
const namedPath = parsedName.join('/');

const path =
options.path ??
joinPathFragments(
projectSourceRoot,
projectType === 'application' ? 'app' : 'lib'
projectType === 'application' ? 'app' : 'lib',
namedPath
);

return {
...options,
name,
type: options.type ?? 'component',
changeDetection: options.changeDetection ?? 'Default',
style: options.style ?? 'css',
path,
projectSourceRoot,
projectRoot: root,
};
}
2 changes: 2 additions & 0 deletions packages/angular/src/generators/component/schema.d.ts
Original file line number Diff line number Diff line change
@@ -17,9 +17,11 @@ export interface Schema {
module?: string;
skipSelector?: boolean;
export?: boolean;
prefix?: string;
}

export interface NormalizedSchema extends Schema {
path: string;
projectSourceRoot: string;
projectRoot: string;
}
5 changes: 5 additions & 0 deletions packages/angular/src/generators/component/schema.json
Original file line number Diff line number Diff line change
@@ -30,6 +30,11 @@
},
"x-prompt": "What name would you like to use for the component?"
},
"prefix": {
"type": "string",
"description": "The prefix to apply to the generated component selector.",
"alias": "p"
},
"displayBlock": {
"description": "Specifies if the style will contain `:host { display: block; }`.",
"type": "boolean",
Original file line number Diff line number Diff line change
@@ -13,15 +13,12 @@ import { CommonModule } from '@angular/common';
templateUrl: './my-lib.component.html',
styleUrls: ['./my-lib.component.css']
})
export class MyLibComponent {
}
export class MyLibComponent {}
"
`;

exports[`lib --angular-14 should generate a library with a standalone component as entry point with angular 14.1.0 3`] = `
"import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyLibComponent } from './my-lib.component';
describe('MyLibComponent', () => {
@@ -59,15 +56,12 @@ import { CommonModule } from '@angular/common';
templateUrl: './my-lib.component.html',
styleUrls: ['./my-lib.component.css']
})
export class MyLibComponent {
}
export class MyLibComponent {}
"
`;
exports[`lib --standalone should generate a library with a standalone component and have it flat 3`] = `
"import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyLibComponent } from './my-lib.component';
describe('MyLibComponent', () => {
@@ -109,15 +103,12 @@ import { CommonModule } from '@angular/common';
templateUrl: './my-lib.component.html',
styleUrls: ['./my-lib.component.css']
})
export class MyLibComponent {
}
export class MyLibComponent {}
"
`;
exports[`lib --standalone should generate a library with a standalone component and have it flat with routing setup 3`] = `
"import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyLibComponent } from './my-lib.component';
describe('MyLibComponent', () => {
@@ -165,15 +156,12 @@ import { CommonModule } from '@angular/common';
templateUrl: './my-lib.component.html',
styleUrls: ['./my-lib.component.css']
})
export class MyLibComponent {
}
export class MyLibComponent {}
"
`;
exports[`lib --standalone should generate a library with a standalone component as entry point 3`] = `
"import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyLibComponent } from './my-lib.component';
describe('MyLibComponent', () => {
@@ -208,19 +196,13 @@ import { CommonModule } from '@angular/common';
selector: 'proj-my-lib',
standalone: true,
imports: [CommonModule],
template: \`
<p>
my-lib works!
</p>
\`,
template: \`<p>my-lib works!</p>\`,
styles: [
],
encapsulation: ViewEncapsulation.ShadowDom,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyLibComponent {
}
export class MyLibComponent {}
"
`;
@@ -234,17 +216,11 @@ import { CommonModule } from '@angular/common';
selector: 'proj-my-lib',
standalone: true,
imports: [CommonModule],
template: \`
<p>
my-lib works!
</p>
\`,
template: \`<p>my-lib works!</p>\`,
styles: [
]
})
export class MyLibComponent {
}
export class MyLibComponent {}
"
`;
@@ -258,23 +234,16 @@ import { CommonModule } from '@angular/common';
selector: 'proj-my-lib',
standalone: true,
imports: [CommonModule],
template: \`
<p>
my-lib works!
</p>
\`,
template: \`<p>my-lib works!</p>\`,
styles: [
]
})
export class MyLibComponent {
}
export class MyLibComponent {}
"
`;
exports[`lib --standalone should generate a library with a standalone component as entry point following SFC pattern 3`] = `
"import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyLibComponent } from './my-lib.component';
describe('MyLibComponent', () => {
@@ -326,15 +295,12 @@ import { CommonModule } from '@angular/common';
templateUrl: './my-lib.component.html',
styleUrls: ['./my-lib.component.css']
})
export class MyLibComponent {
}
export class MyLibComponent {}
"
`;
exports[`lib --standalone should generate a library with a standalone component as entry point with routing setup 4`] = `
"import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyLibComponent } from './my-lib.component';
describe('MyLibComponent', () => {
@@ -444,15 +410,12 @@ import { CommonModule } from '@angular/common';
templateUrl: './my-dir-my-lib.component.html',
styleUrls: ['./my-dir-my-lib.component.css']
})
export class MyDirMyLibComponent {
}
export class MyDirMyLibComponent {}
"
`;
exports[`lib --standalone should generate a library with a standalone component in a directory 3`] = `
"import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyDirMyLibComponent } from './my-dir-my-lib.component';
describe('MyDirMyLibComponent', () => {
@@ -490,15 +453,12 @@ import { CommonModule } from '@angular/common';
templateUrl: './my-lib.component.html',
styleUrls: ['./my-lib.component.css']
})
export class MyLibComponent {
}
export class MyLibComponent {}
"
`;
exports[`lib --standalone should generate a library with a standalone component in a directory with a simple name 3`] = `
"import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyLibComponent } from './my-lib.component';
describe('MyLibComponent', () => {
6 changes: 5 additions & 1 deletion packages/angular/src/generators/utils/find-module.ts
Original file line number Diff line number Diff line change
@@ -13,7 +13,7 @@ let tsModule: typeof import('typescript');
export function findModule(tree: Tree, path: string, module?: string) {
let modulePath = '';
let pathToSearch = path;
while (pathToSearch !== '/') {
while (pathToSearch !== '.' && pathToSearch !== '/') {
if (module) {
const pathToModule = joinPathFragments(pathToSearch, module);
if (tree.exists(pathToModule)) {
@@ -36,6 +36,10 @@ export function findModule(tree: Tree, path: string, module?: string) {
pathToSearch = dirname(pathToSearch);
}

if (modulePath === '') {
throw new Error('Could not find a declaring module file.');
}

const moduleContents = tree.read(modulePath, 'utf-8');
if (!moduleContents.includes('@NgModule')) {
throw new Error(

1 comment on commit 4dbe6a5

@vercel
Copy link

@vercel vercel bot commented on 4dbe6a5 Mar 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

nx-dev – ./

nx.dev
nx-five.vercel.app
nx-dev-nrwl.vercel.app
nx-dev-git-master-nrwl.vercel.app

Please sign in to comment.