Use Angular 2 without Reflect.js and zone.js in Browser

1.1k views Asked by At

I am trying to use Angular within an existing typescript project, where I am using browserify to bundle the actual app.

Now, i have basically just rebuilt the app from the setup tutorial and managed to get it all working:

angular/app/app.component.ts

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    template: `<h1>Hello {{name}}</h1>`
})
export class AppComponent { name = 'Angular'; }

angular/app/app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }  from './app.component';

@NgModule({
    imports: [BrowserModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }

angular/app/main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule }              from './app.module';

export function render () {    
    platformBrowserDynamic().bootstrapModule(AppModule);    
}

And finally my Bundle-facade which gets compiled to a standanlone-bundle via browserify:

my-app.ts

import { render } from "./angular/app/main";

export = {
    testAngular: render  // This is the function that I call in my HTML page
}

The only thing that bugs me a lot is that I have to add

<script src="path/to/zone.js"></script>
<script src="path/to/Reflect.js"></script>

to every html page that uses my bundled angular modules to get rid of errors due to class decorators in my angular app:

Uncaught reflect-metadata shim is required when using class decorators

Is there a way to get rid of this or make both of those Modules Part of my bundle by some kind of import statement?

Or is there any other best practice to handle the problem those shims are solving?

2

There are 2 answers

0
nozzleman On BEST ANSWER

I managed to resolve this by adding

import 'zone.js';
import 'reflect-metadata';

on top (!!) of my-app.ts (by bundle root file).

0
akhalid7 On

Relevant to the accepted answer but didn't have the reputation to comment

you should not import zone.js from your application like this. If you do, you are loading the prolyfill too late which means that part of your environment (module loader) won't be under the oversight of zone.js - things might seem to work for a while but sooner or later you'll run into issues when updates to the ui stop happening and you won't know why.

For this reason it's better to always include all polyfills before any module loader (systemjs) or application code. This is why we recommend loading zones as the first script in index.html.

From github: issue and comment

In short add the zone.js and reflect.js in the index.html. You should have had to write the script files once only inside of the index page (every other page loads inside of the index page and therefore zone and reflect.js is already loaded for them.