test(ivy): switch HelloWorld to ivy compiler (#22788)

PR Close #22788
This commit is contained in:
Misko Hevery 2018-03-14 21:32:09 -07:00 committed by Miško Hevery
parent bfe077ad64
commit fc50c77bd3
10 changed files with 135 additions and 26 deletions

View File

@ -2,9 +2,9 @@ workspace(name = "angular")
http_archive( http_archive(
name = "build_bazel_rules_nodejs", name = "build_bazel_rules_nodejs",
url = "https://github.com/bazelbuild/rules_nodejs/archive/0.5.3.zip", url = "https://github.com/bazelbuild/rules_nodejs/archive/25bb70fb67bddcc257b869f434ccc0fd130ec3bd.zip",
strip_prefix = "rules_nodejs-0.5.3", strip_prefix = "rules_nodejs-25bb70fb67bddcc257b869f434ccc0fd130ec3bd",
sha256 = "17a5515f59777b00cb25dbc710017a14273f825029b2ec60e0969d28914870be", sha256 = "11c0d73bdcb4b2608abbe5967be5a910bdaebf848eb13e4e7f8413bbdeb940b8",
) )
load("@build_bazel_rules_nodejs//:defs.bzl", "check_bazel_version", "node_repositories") load("@build_bazel_rules_nodejs//:defs.bzl", "check_bazel_version", "node_repositories")

View File

@ -52,6 +52,15 @@ export function assertNotNull<T>(actual: T, msg: string) {
} }
} }
export function assertComponentType(
actual: any,
msg: string =
'Type passed in is not ComponentType, it does not have \'ngComponentDef\' property.') {
if (!actual.ngComponentDef) {
throwError(msg);
}
}
function throwError(msg: string): never { function throwError(msg: string): never {
throw new Error(`ASSERTION ERROR: ${msg}`); throw new Error(`ASSERTION ERROR: ${msg}`);
} }

View File

@ -8,10 +8,11 @@
// We are temporarily importing the existing viewEngine from core so we can be sure we are // We are temporarily importing the existing viewEngine from core so we can be sure we are
// correctly implementing its interfaces for backwards compatibility. // correctly implementing its interfaces for backwards compatibility.
import {Type} from '../core';
import {Injector} from '../di/injector'; import {Injector} from '../di/injector';
import {ComponentRef as viewEngine_ComponentRef} from '../linker/component_factory'; import {ComponentRef as viewEngine_ComponentRef} from '../linker/component_factory';
import {assertNotNull} from './assert'; import {assertComponentType, assertNotNull} from './assert';
import {queueInitHooks, queueLifecycleHooks} from './hooks'; import {queueInitHooks, queueLifecycleHooks} from './hooks';
import {CLEAN_PROMISE, _getComponentHostLElementNode, baseDirectiveCreate, createLView, createTView, enterView, getRootView, hostElement, initChangeDetectorIfExisting, locateHostElement, renderComponentOrTemplate} from './instructions'; import {CLEAN_PROMISE, _getComponentHostLElementNode, baseDirectiveCreate, createLView, createTView, enterView, getRootView, hostElement, initChangeDetectorIfExisting, locateHostElement, renderComponentOrTemplate} from './instructions';
import {ComponentDef, ComponentType} from './interfaces/definition'; import {ComponentDef, ComponentType} from './interfaces/definition';
@ -113,9 +114,13 @@ export const NULL_INJECTOR: Injector = {
* @param options Optional parameters which control bootstrapping * @param options Optional parameters which control bootstrapping
*/ */
export function renderComponent<T>( export function renderComponent<T>(
componentType: ComponentType<T>, opts: CreateComponentOptions = {}): T { componentType: ComponentType<T>|
Type<T>/* Type as workaround for: Microsoft/TypeScript/issues/4881 */
,
opts: CreateComponentOptions = {}): T {
ngDevMode && assertComponentType(componentType);
const rendererFactory = opts.rendererFactory || domRendererFactory3; const rendererFactory = opts.rendererFactory || domRendererFactory3;
const componentDef = componentType.ngComponentDef as ComponentDef<T>; const componentDef = (componentType as ComponentType<T>).ngComponentDef as ComponentDef<T>;
if (componentDef.type != componentType) componentDef.type = componentType; if (componentDef.type != componentType) componentDef.type = componentType;
let component: T; let component: T;
const hostNode = locateHostElement(rendererFactory, opts.host || componentDef.tag); const hostNode = locateHostElement(rendererFactory, opts.host || componentDef.tag);
@ -135,7 +140,7 @@ export function renderComponent<T>(
try { try {
// Create element node at index 0 in data array // Create element node at index 0 in data array
elementNode = hostElement(hostNode, componentDef); elementNode = hostElement(hostNode, componentDef);
// Create directive instance with n() and store at index 1 in data array (el is 0) // Create directive instance with factory() and store at index 1 in data array (el is 0)
component = rootContext.component = component = rootContext.component =
baseDirectiveCreate(1, componentDef.factory(), componentDef) as T; baseDirectiveCreate(1, componentDef.factory(), componentDef) as T;
initChangeDetectorIfExisting(elementNode.nodeInjector, component); initChangeDetectorIfExisting(elementNode.nodeInjector, component);

View File

@ -1,11 +1,12 @@
package(default_visibility = ["//visibility:public"]) package(default_visibility = ["//visibility:public"])
load("//tools:defaults.bzl", "ts_library") load("//tools:defaults.bzl", "ts_library", "ivy_ng_module")
load("//tools/symbol-extractor:index.bzl", "js_expected_symbol_test") load("//tools/symbol-extractor:index.bzl", "js_expected_symbol_test")
load("//packages/bazel/src:ng_rollup_bundle.bzl", "ng_rollup_bundle") load("//packages/bazel/src:ng_rollup_bundle.bzl", "ng_rollup_bundle")
load("@build_bazel_rules_nodejs//:defs.bzl", "jasmine_node_test") load("@build_bazel_rules_nodejs//:defs.bzl", "jasmine_node_test")
load("@build_bazel_rules_typescript//:defs.bzl", "ts_devserver")
ts_library( ivy_ng_module(
name = "hello_world", name = "hello_world",
srcs = ["index.ts"], srcs = ["index.ts"],
deps = [ deps = [
@ -54,3 +55,13 @@ js_expected_symbol_test(
src = ":bundle.min_debug.js", src = ":bundle.min_debug.js",
golden = ":bundle.golden_symbols.json", golden = ":bundle.golden_symbols.json",
) )
ts_devserver(
name = "devserver",
static_files = [
":bundle.min_debug.js",
":bundle.min.js",
"index.html",
],
deps = [],
)

View File

@ -8,6 +8,12 @@
{ {
"name": "EMPTY_RENDERER_TYPE_ID" "name": "EMPTY_RENDERER_TYPE_ID"
}, },
{
"name": "HelloWorld"
},
{
"name": "INeedToExistEvenThoughtIAmNotNeeded"
},
{ {
"name": "NG_HOST_SYMBOL" "name": "NG_HOST_SYMBOL"
}, },
@ -68,6 +74,9 @@
{ {
"name": "defineComponent" "name": "defineComponent"
}, },
{
"name": "defineInjector"
},
{ {
"name": "detectChangesInternal" "name": "detectChangesInternal"
}, },

View File

@ -0,0 +1,31 @@
<!doctype html>
<html>
<head>
<title>Angular Hello World Example</title>
</head>
<body>
<!-- The Angular application will be bootstrapped into this element. -->
<hello-world></hello-world>
<!--
Script tag which bootstraps the application. Use `?debug` in URL to select
the debug version of the script.
There are two scripts sources: `bundle.min.js` and `bundle.min_debug.js` You can
switch between which bundle the browser loads to experiment with the application.
- `bundle.min.js`: Is what the site would serve to their users. It has gone
through rollup, build-optimizer, and uglify with tree shaking.
- `bundle.min_debug.js`: Is what the developer would like to see when debugging
the application. It has also done through full pipeline of rollup, build-optimizer,
and uglify, however special flags were passed to uglify to prevent inlining and
property renaming.
-->
<script>
document.write('<script src="' +
(document.location.search.endsWith('debug') ? '/bundle.min_debug.js' : '/bundle.min.js') +
'"></' + 'script>');
</script>
</body>
</html>

View File

@ -6,19 +6,16 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
import {ɵT as T, ɵdefineComponent as defineComponent, ɵrenderComponent as renderComponent} from '@angular/core'; import {Component, NgModule, ɵrenderComponent as renderComponent} from '@angular/core';
class HelloWorld { @Component({selector: 'hello-world', template: 'Hello World!'})
static ngComponentDef = defineComponent({ export class HelloWorld {
type: HelloWorld,
tag: 'hello-world',
factory: () => new HelloWorld(),
template: function HelloWorldTemplate(ctx: HelloWorld, cm: boolean) {
if (cm) {
T(0, 'Hello World!');
}
}
});
} }
// TODO(misko): Forgetting to export HelloWorld and not having NgModule fails silently.
@NgModule({declarations: [HelloWorld]})
export class INeedToExistEvenThoughtIAmNotNeeded {
}
// TODO(misko): Package should not be required to make this work.
renderComponent(HelloWorld); renderComponent(HelloWorld);

View File

@ -22,15 +22,17 @@ export class SymbolExtractor {
static parse(path: string, contents: string): Symbol[] { static parse(path: string, contents: string): Symbol[] {
const symbols: Symbol[] = []; const symbols: Symbol[] = [];
const source: ts.SourceFile = ts.createSourceFile(path, contents, ts.ScriptTarget.Latest, true); const source: ts.SourceFile = ts.createSourceFile(path, contents, ts.ScriptTarget.Latest, true);
let fnDepth = 0; let fnRecurseDepth = 0;
function visitor(child: ts.Node) { function visitor(child: ts.Node) {
// Left for easier debugging.
// console.log('>>>', ts.SyntaxKind[child.kind]);
switch (child.kind) { switch (child.kind) {
case ts.SyntaxKind.FunctionExpression: case ts.SyntaxKind.FunctionExpression:
fnDepth++; fnRecurseDepth++;
if (fnDepth <= 1) { if (fnRecurseDepth <= 1) {
// Only go into function expression once for the outer closure.
ts.forEachChild(child, visitor); ts.forEachChild(child, visitor);
} }
fnRecurseDepth--;
break; break;
case ts.SyntaxKind.SourceFile: case ts.SyntaxKind.SourceFile:
case ts.SyntaxKind.VariableStatement: case ts.SyntaxKind.VariableStatement:
@ -44,9 +46,13 @@ export class SymbolExtractor {
break; break;
case ts.SyntaxKind.VariableDeclaration: case ts.SyntaxKind.VariableDeclaration:
const varDecl = child as ts.VariableDeclaration; const varDecl = child as ts.VariableDeclaration;
if (varDecl.initializer) { if (varDecl.initializer && fnRecurseDepth !== 0) {
symbols.push({name: varDecl.name.getText()}); symbols.push({name: varDecl.name.getText()});
} }
if (fnRecurseDepth == 0 &&
isRollupExportSymbol(child.parent as ts.VariableDeclarationList)) {
ts.forEachChild(child, visitor);
}
break; break;
case ts.SyntaxKind.FunctionDeclaration: case ts.SyntaxKind.FunctionDeclaration:
const funcDecl = child as ts.FunctionDeclaration; const funcDecl = child as ts.FunctionDeclaration;
@ -114,3 +120,15 @@ function toSymbol(v: string | Symbol): Symbol {
function toName(symbol: Symbol): string { function toName(symbol: Symbol): string {
return symbol.name; return symbol.name;
} }
/**
* Detects if VariableDeclarationList is format `var x = function(){}()`;
*
* Rollup produces this format when it wants to export symbols from a bundle.
* @param child
*/
function isRollupExportSymbol(child: ts.VariableDeclarationList): boolean {
if (child.declarations.length !== 1) return false;
const decl: ts.VariableDeclaration = child.declarations[0];
return !!(decl.initializer && decl.initializer.kind == ts.SyntaxKind.CallExpression);
}

View File

@ -0,0 +1,26 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Rollup exports symbols in this particular way. This test demonstrates that we can correctly read
* symbols.
*/
var fooBar = function(exports) {
'use strict';
// tslint:disable-next-line:no-console
console.log('Hello, Alice in Wonderland');
var A = function() {
function A() {}
A.prototype.a = function() { return document.a; };
return A;
}();
// tslint:disable-next-line:no-console
console.error(new A().a());
exports.A = A;
return exports;
}({});

View File

@ -0,0 +1,3 @@
[
"A"
]