Skip to content

refactor(NgModule): update to RC5 #1579

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 1 commit into from
Aug 9, 2016
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
28 changes: 23 additions & 5 deletions addon/ng2/blueprints/component/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ var dynamicPathParser = require('../../utilities/dynamic-path-parser');
var addBarrelRegistration = require('../../utilities/barrel-management');
var getFiles = Blueprint.prototype.files;
const stringUtils = require('ember-cli-string-utils');
const astUtils = require('../../utilities/ast-utils');

module.exports = {
description: '',
Expand Down Expand Up @@ -119,13 +120,30 @@ module.exports = {
return;
}

var returns = [];
var modulePath = path.resolve(process.env.PWD, this.dynamicPath.appRoot, 'app.module.ts');
var classifiedName =
stringUtils.classify(`${options.entity.name}-${options.originBlueprintName}`);
var importPath = `'./${options.entity.name}/` +
stringUtils.dasherize(`${options.entity.name}.component';`);

if (!options.flat) {
return addBarrelRegistration(this, this.generatePath);
returns.push(function() {
return addBarrelRegistration(this, this.generatePath)
});
} else {
return addBarrelRegistration(
this,
this.generatePath,
options.entity.name + '.component');
returns.push(function() {
return addBarrelRegistration(
this,
this.generatePath,
options.entity.name + '.component')
});
}

if (!options['skip-import']) {
returns.push(astUtils.importComponent(modulePath, classifiedName, importPath));
}

return Promise.all(returns);
}
};
30 changes: 23 additions & 7 deletions addon/ng2/blueprints/directive/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ var Blueprint = require('ember-cli/lib/models/blueprint');
var dynamicPathParser = require('../../utilities/dynamic-path-parser');
var addBarrelRegistration = require('../../utilities/barrel-management');
var getFiles = Blueprint.prototype.files;
const stringUtils = require('ember-cli-string-utils');
const astUtils = require('../../utilities/ast-utils');

module.exports = {
description: '',
Expand Down Expand Up @@ -52,15 +54,29 @@ module.exports = {
},

afterInstall: function(options) {
var returns = [];
var modulePath = path.resolve(process.env.PWD, this.dynamicPath.appRoot, 'app.module.ts');
var classifiedName =
stringUtils.classify(options.entity.name);
var importPath = '\'./' + stringUtils.dasherize(`${options.entity.name}.directive';`);

if (!options.flat) {
return addBarrelRegistration(
this,
this.generatePath);
returns.push(function() {
return addBarrelRegistration(this, this.generatePath)
});
} else {
return addBarrelRegistration(
this,
this.generatePath,
options.entity.name + '.directive');
returns.push(function() {
return addBarrelRegistration(
this,
this.generatePath,
options.entity.name + '.directive')
});
}

if (!options['skip-import']) {
returns.push(astUtils.importComponent(modulePath, classifiedName, importPath));
}

return Promise.all(returns);
}
};
23 changes: 23 additions & 0 deletions addon/ng2/blueprints/ng2/files/__path__/app/app.module.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ApplicationRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';<% if (isMobile) { %>
import { AppShellModule } from '../app-shell-module';<% } %>

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
CommonModule,
FormsModule<% if (isMobile) { %>,
AppShellModule<% } %>
],
entryComponents: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule {

}
1 change: 1 addition & 0 deletions addon/ng2/blueprints/ng2/files/__path__/app/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './environments/environment';
export * from './app.component';
export * from './app.module';
7 changes: 3 additions & 4 deletions addon/ng2/blueprints/ng2/files/__path__/main.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { bootstrap } from '@angular/platform-browser-dynamic';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { AppComponent, environment } from './app/';<% if(isMobile) { %>
import { APP_SHELL_RUNTIME_PROVIDERS } from '@angular/app-shell';<% } %>
import { AppModule, environment } from './app/';

if (environment.production) {
enableProdMode();
}

bootstrap(AppComponent<% if(isMobile) { %>, [ APP_SHELL_RUNTIME_PROVIDERS ]<% } %>);
platformBrowserDynamic().bootstrapModule(AppModule);
16 changes: 8 additions & 8 deletions addon/ng2/blueprints/ng2/files/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
},
"private": true,
"dependencies": {
"@angular/common": "2.0.0-rc.4",
"@angular/compiler": "2.0.0-rc.4",
"@angular/core": "2.0.0-rc.4",
"@angular/forms": "0.2.0",
"@angular/http": "2.0.0-rc.4",
"@angular/platform-browser": "2.0.0-rc.4",
"@angular/platform-browser-dynamic": "2.0.0-rc.4",
"@angular/router": "3.0.0-beta.2",
"@angular/common": "github:angular/common-builds",
"@angular/compiler": "github:angular/compiler-builds",
"@angular/core": "github:angular/core-builds",
"@angular/forms": "github:angular/forms-builds",
"@angular/http": "github:angular/http-builds",
"@angular/platform-browser": "github:angular/platform-browser-builds",
"@angular/platform-browser-dynamic": "github:angular/platform-browser-dynamic-builds",
"@angular/router": "github:angular/router-builds",
"core-js": "^2.4.0",
"reflect-metadata": "0.1.3",
"rxjs": "5.0.0-beta.6",
Expand Down
30 changes: 23 additions & 7 deletions addon/ng2/blueprints/pipe/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ var Blueprint = require('ember-cli/lib/models/blueprint');
var dynamicPathParser = require('../../utilities/dynamic-path-parser');
var addBarrelRegistration = require('../../utilities/barrel-management');
var getFiles = Blueprint.prototype.files;
const stringUtils = require('ember-cli-string-utils');
const astUtils = require('../../utilities/ast-utils');

module.exports = {
description: '',
Expand Down Expand Up @@ -50,15 +52,29 @@ module.exports = {
},

afterInstall: function(options) {
var returns = [];
var modulePath = path.resolve(process.env.PWD, this.dynamicPath.appRoot, 'app.module.ts');
var classifiedName =
stringUtils.classify(`${options.entity.name}-${options.originBlueprintName}`);
var importPath = '\'./' + stringUtils.dasherize(`${options.entity.name}.pipe';`);

if (!options.flat) {
return addBarrelRegistration(
this,
this.generatePath);
returns.push(function() {
return addBarrelRegistration(this, this.generatePath)
});
} else {
return addBarrelRegistration(
this,
this.generatePath,
options.entity.name + '.pipe');
returns.push(function() {
return addBarrelRegistration(
this,
this.generatePath,
options.entity.name + '.pipe')
});
}

if (!options['skip-import']) {
returns.push(astUtils.importComponent(modulePath, classifiedName, importPath));
}

return Promise.all(returns);
}
};
70 changes: 69 additions & 1 deletion addon/ng2/utilities/ast-utils.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
import * as ts from 'typescript';
import * as fs from 'fs';
import { InsertChange } from './change';

/**
* Get TS source file based on path.
* @param filePath
* @return source file of ts.SourceFile kind
*/
export function getSource(filePath: string): ts.SourceFile {
return ts.createSourceFile(filePath, fs.readFileSync(filePath).toString(),
ts.ScriptTarget.ES6, true);
}

/**
* Find all nodes from the AST in the subtree of node of SyntaxKind kind.
* @param node
* @param kind
* @return all nodes of kind kind, or [] if none is found
* @return all nodes of kind, or [] if none is found
*/
export function findNodes(node: ts.Node, kind: ts.SyntaxKind): ts.Node[] {
if (!node) {
Expand All @@ -19,6 +30,26 @@ export function findNodes(node: ts.Node, kind: ts.SyntaxKind): ts.Node[] {
foundNodes.concat(findNodes(child, kind)), arr);
}

/**
* Find all nodes from the AST in the subtree based on text.
* @param node
* @param text
* @return all nodes of text, or [] if none is found
*/
export function findNodesByText(node: ts.Node, text: string): ts.Node[] {
if (!node) {
return [];
}
let arr: ts.Node[] = [];
if (node.getText() === text) {
arr.push(node);
}

return node.getChildren().reduce((foundNodes, child) => {
return foundNodes.concat(findNodesByText(child, text));
}, arr);
}

/**
* Helper for sorting nodes.
* @return function to sort nodes in increasing order of position in sourceFile
Expand Down Expand Up @@ -52,3 +83,40 @@ export function insertAfterLastOccurrence(nodes: ts.Node[], toInsert: string,
let lastItemPosition: number = lastItem ? lastItem.end : fallbackPos;
return new InsertChange(file, lastItemPosition, toInsert);
}

/**
* Custom function to insert component (component, pipe, directive)
* into NgModule declarations. It also imports the component.
* @param modulePath
* @param classifiedName
* @param importPath
* @return Promise
*/
export function importComponent(modulePath: string, classifiedName: string,
importPath: string): Promise<void> {
let source: ts.SourceFile = this.getSource(modulePath);

let importNode: ts.Node =
this.findNodesByText(source, 'import').pop();
let iPos: ts.LineAndCharacter =
Copy link
Contributor

Choose a reason for hiding this comment

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

Name these pos, line, start and str.

source.getLineAndCharacterOfPosition(importNode.getEnd());
let iLine: number = iPos.line + 1;
let iStart: number = source.getPositionOfLineAndCharacter(iLine, 0);
let iStr: string = `import { ${classifiedName} } from ${importPath}\n`;
let changeImport: InsertChange = new InsertChange(modulePath, iStart, iStr);

return changeImport.apply().then(() => {
source = this.getSource(modulePath);
Copy link
Contributor

Choose a reason for hiding this comment

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

No this. Just call getSource().

let declarationsNode: ts.Node =
this.findNodesByText(source, 'declarations').shift();
Copy link
Contributor

Choose a reason for hiding this comment

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

Unfortunately, this will fail on a number of things, including an import {declarations} from 'x' and var declarations = foo;. I would suggest looking for the @NgModule call, take the first argument, then look for the declarations key. Also, please make sure the declarations is actually there (maybe it's not) and an array declaration.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Good point. Thanks

let dPos: ts.LineAndCharacter =
Copy link
Contributor

Choose a reason for hiding this comment

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

You can redeclare pos, ... since let is scope limited.

source.getLineAndCharacterOfPosition(declarationsNode.getEnd());
let dStart: number =
source.getPositionOfLineAndCharacter(dPos.line + 1, -1);
let dStr: string = `\n ${classifiedName},`;
let changeDeclarations: InsertChange = new InsertChange(modulePath, dStart, dStr);

return changeDeclarations.apply();
});
}