Skip to content

Manually import newly created components in the right NgModules #79

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Aug 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ jasmine-config/**/*.js.map
# IDEs
.idea/
jsconfig.json
.vscode/
.history

# Misc
Expand Down
17 changes: 17 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Test",
"program": "${workspaceFolder}/node_modules/jasmine/bin/jasmine.js",
"args": [
"--config=jasmine-config/jasmine.json"
],
"outFiles": [
"${workspaceFolder}/**/*.js"
]
}
]
}
29 changes: 0 additions & 29 deletions src/ast-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,22 +22,6 @@ class RemoveContent implements Node {
}
}

export function addSymbolToComponentMetadata(
source: ts.SourceFile,
componentPath: string,
metadataField: string,
symbolName: string,
): Change[] {
return addSymbolToDecoratorMetadata(
source,
componentPath,
metadataField,
symbolName,
'Component',
'@angular/core'
);
}

// Almost identical to addSymbolToNgModuleMetadata from @schematics/angular/utility/ast-utils
// the method can be refactored so that it can be used with custom decorators
export function addSymbolToDecoratorMetadata(
Expand Down Expand Up @@ -630,19 +614,6 @@ export function findImportPath(source: ts.Node, name) {
return moduleSpecifier.text;
}

export const insertModuleId = (tree: Tree, component: string) => {
const componentSource = getSourceFile(tree, component);
const recorder = tree.beginUpdate(component);

const metadataChange = addSymbolToComponentMetadata(
componentSource, component, 'moduleId', 'module.id');

metadataChange.forEach((change: InsertChange) =>
recorder.insertRight(change.pos, change.toAdd)
);
tree.commitUpdate(recorder);

};

export const updateNodeText = (tree: Tree, node: ts.Node, newText: string) => {
const recorder = tree.beginUpdate(node.getSourceFile().fileName);
Expand Down
87 changes: 87 additions & 0 deletions src/generate/component/ast-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import * as ts from 'typescript';

import { SchematicsException, Tree } from '@angular-devkit/schematics';
import { classify } from '@angular-devkit/core/src/utils/strings';
import { buildRelativePath } from '@schematics/angular/utility/find-module';
import { InsertChange, Change } from '@schematics/angular/utility/change';
import { addEntryComponentToModule, addExportToModule, addDeclarationToModule } from '@schematics/angular/utility/ast-utils';
import { Schema as ComponentOptions } from './schema';
import { getSourceFile } from '../../utils';
import { addSymbolToDecoratorMetadata } from '../../ast-utils';

export const insertModuleId = (tree: Tree, component: string) => {
const componentSource = getSourceFile(tree, component);
const recorder = tree.beginUpdate(component);

const metadataChange = addSymbolToComponentMetadata(
componentSource, component, 'moduleId', 'module.id');

metadataChange.forEach((change: InsertChange) =>
recorder.insertRight(change.pos, change.toAdd)
);
tree.commitUpdate(recorder);
};

function addSymbolToComponentMetadata(
source: ts.SourceFile,
componentPath: string,
metadataField: string,
symbolName: string,
): Change[] {
return addSymbolToDecoratorMetadata(
source,
componentPath,
metadataField,
symbolName,
'Component',
'@angular/core'
);
}

export function addDeclarationToNgModule(tree: Tree, options: ComponentOptions, componentPath: string, modulePath: string) {
const source = readIntoSourceFile(tree, modulePath);
const relativePath = buildRelativePath(modulePath, componentPath);
const classifiedName = classify(`${options.name}Component`);
const declarationChanges = addDeclarationToModule(source, modulePath, classifiedName, relativePath);
const declarationRecorder = tree.beginUpdate(modulePath);
for (const change of declarationChanges) {
if (change instanceof InsertChange) {
declarationRecorder.insertLeft(change.pos, change.toAdd);
}
}
tree.commitUpdate(declarationRecorder);
if (options.export) {
// Need to refresh the AST because we overwrote the file in the host.
const source = readIntoSourceFile(tree, modulePath);
const exportRecorder = tree.beginUpdate(modulePath);
const exportChanges = addExportToModule(source, modulePath, classify(`${options.name}Component`), relativePath);
for (const change of exportChanges) {
if (change instanceof InsertChange) {
exportRecorder.insertLeft(change.pos, change.toAdd);
}
}
tree.commitUpdate(exportRecorder);
}
if (options.entryComponent) {
// Need to refresh the AST because we overwrote the file in the host.
const source = readIntoSourceFile(tree, modulePath);
const entryComponentRecorder = tree.beginUpdate(modulePath);
const entryComponentChanges = addEntryComponentToModule(source, modulePath, classify(`${options.name}Component`), relativePath);
for (const change of entryComponentChanges) {
if (change instanceof InsertChange) {
entryComponentRecorder.insertLeft(change.pos, change.toAdd);
}
}
tree.commitUpdate(entryComponentRecorder);
}
}

function readIntoSourceFile(host: Tree, modulePath: string): ts.SourceFile {
const text = host.read(modulePath);
if (text === null) {
throw new SchematicsException(`File ${modulePath} does not exist.`);
}
const sourceText = text.toString('utf-8');

return ts.createSourceFile(modulePath, sourceText, ts.ScriptTarget.Latest, true);
}
60 changes: 60 additions & 0 deletions src/generate/component/find-module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { dirname } from 'path';

import { Tree, DirEntry } from "@angular-devkit/schematics";
import { join, normalize } from '@angular-devkit/core';
import { dasherize } from '@angular-devkit/core/src/utils/strings';

import { Schema as ComponentOptions } from './schema';

export function findModule(tree: Tree, options: ComponentOptions, path: string, extension: string) {
if (options.module) {
return findExplicitModule(tree, path, extension, options.module);
} else {
const pathToCheck = (path || '')
+ (options.flat ? '' : '/' + dasherize(options.name));

return findImplicitModule(tree, pathToCheck, extension);
}
}

function findExplicitModule(tree: Tree, path: string, extension: string, moduleName: string) {
while (path) {
const modulePath = normalize(`/${path}/${moduleName}`);
const moduleBaseName = normalize(modulePath).split('/').pop();

if (tree.exists(modulePath)) {
return normalize(modulePath);
} else if (tree.exists(modulePath + extension + '.ts')) {
return normalize(modulePath + extension + '.ts');
} else if (tree.exists(modulePath + '.module' + extension + '.ts')) {
return normalize(modulePath + '.module' + extension + '.ts');
} else if (tree.exists(modulePath + '/' + moduleBaseName + '.module' + extension + '.ts')) {
return normalize(modulePath + '/' + moduleBaseName + '.module' + extension + '.ts');
}

path = dirname(path);
}

throw new Error('Specified module does not exist');
}

function findImplicitModule(tree: Tree, path: string, extension: string) {
let dir: DirEntry | null = tree.getDir(`/${path}`);

const moduleRe = new RegExp(`.module${extension}.ts`);
const routingModuleRe = new RegExp(`-routing.module${extension}.ts`);

while (dir) {
const matches = dir.subfiles.filter(p => moduleRe.test(p) && !routingModuleRe.test(p));
if (matches.length == 1) {
return join(dir.path, matches[0]);
} else if (matches.length > 1) {
throw new Error('More than one module matches. Use skip-import option to skip importing '
+ 'the component into the closest module.');
}

dir = dir.parent;
}
throw new Error('Could not find an NgModule. Use the skip-import '
+ 'option to skip importing in NgModule.');
}
37 changes: 29 additions & 8 deletions src/generate/component/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { dirname } from 'path';

import {
Rule,
SchematicContext,
Expand All @@ -11,14 +13,17 @@ import {
mergeWith,
TemplateOptions,
filter,
DirEntry,
} from '@angular-devkit/schematics';

import { insertModuleId } from '../../ast-utils';
import { Schema as ComponentOptions } from './schema';
import { dasherize } from '@angular-devkit/core/src/utils/strings';
import { Path } from '@angular-devkit/core';
import { parseName } from '@schematics/angular/utility/parse-name';

import { Extensions, getExtensions, removeNsSchemaOptions, PlatformUse, getPlatformUse, validateGenerateOptions } from '../utils';
import { Path } from '@angular-devkit/core';
import { addDeclarationToNgModule, insertModuleId } from './ast-utils';
import { Schema as ComponentOptions } from './schema';
import { findModule } from './find-module';

class ComponentInfo {
classPath: string;
Expand Down Expand Up @@ -48,14 +53,32 @@ export default function (options: ComponentOptions): Rule {
return tree;
},

() => {
return externalSchematic('@schematics/angular', 'component', removeNsSchemaOptions(options));
},
() => externalSchematic('@schematics/angular', 'component', removeNsSchemaOptions({ ...options, skipImport: true })),

(tree: Tree) => {
extensions = getExtensions(tree, options);
componentInfo = parseComponentInfo(tree, options);
},

(tree: Tree) => {
if (options.skipImport) {
return tree;
}

const componentPath = componentInfo.classPath;
const componentDir = dirname(componentPath);
if (platformUse.useWeb) {
const webModule = findModule(tree, options, componentDir, extensions.web);
addDeclarationToNgModule(tree, options, componentPath, webModule);
}

if (platformUse.useNs) {
const nsModule = findModule(tree, options, componentDir, extensions.ns);
addDeclarationToNgModule(tree, options, componentPath, nsModule);
}

return tree;
},

(tree: Tree) => {
if (platformUse.nsOnly) {
Expand Down Expand Up @@ -86,7 +109,6 @@ const validateGenerateComponentOptions = (platformUse: PlatformUse, options: Com
};

const parseComponentInfo = (tree: Tree, options: ComponentOptions): ComponentInfo => {
// const path = `/${projectSettings.root}/${projectSettings.sourceRoot}/app`;
const component = new ComponentInfo();

const parsedPath = parseName(options.path || '', options.name);
Expand Down Expand Up @@ -139,5 +161,4 @@ const addNativeScriptFiles = (component: ComponentInfo) => {
]);

return mergeWith(templateSource);

};
Loading