Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Real World Angular: Erfahrungen von der Projektfront

Real World Angular: Erfahrungen von der Projektfront

Angular 2 eignet sich prima zur Entwicklung großer webbasierter Anwendungen. Dazu gibt das SPA-Framework Programmierern diverse APIs und Werkzeuge an die Hand. In der Dokumentation und den Tutorials von Angular 2 werden diese anhand kleiner Beispiele erklärt. Real-World-Projekte sind mit diesen Minibeispielen aber natürlich nicht zu vergleichen: Dort gibt es dann doch einiges mehr zu beachten, als uns die Dokumentation zunächst verrät. Christian Liebel von Thinktecture zeigt Ihnen anhand ausgesuchter praktischer Beispiele aus der realen Projektwelt, was Sie bei der Entwicklung mit Angular 2 zum Beispiel hinsichtlich Build-Prozess, Performance, Bundling, weiterer Optimierungen oder bestmöglicher Cross-Plattform-Unterstützung beachten müssen.

Christian Liebel

February 23, 2017
Tweet

More Decks by Christian Liebel

Other Decks in Programming

Transcript

  1. Real World Angular Erfahrungen von der Projektfront Was Sie nicht

    erwartet Einführung/Grundlagen von Angular, Single-Page Web Applications oder JavaScript Lösungen, die zu 100% auf Ihren Anwendungsfall übertragbar sind Was Sie erwartet Vier praktische Beispiele von der Projektfront Problemanalysen, sofern anwendbar Produktionsreife Lösungsansätze
  2. Real World Angular Erfahrungen von der Projektfront Christian Liebel Thinktecture

    AG Microsoft MVP Visual Studio and Development Technologies Twitter: @chris_liebel E-Mail: [email protected] https://thinktecture.com https://christianliebel.com Gestatten?
  3. Cross-Platform Support • Single-Page Applications • Handling Platform Differences Build

    Process • Angular CLI • Custom Build Bundling • Ahead of Time Compilation • Tree Shaking Performance • Change Detection Strategies • NgZone Real World Angular Erfahrungen von der Projektfront
  4. Real World Angular Erfahrungen von der Projektfront The Problem Diversity

    of devices and platforms Resources (personnel, time, money) are limited “Write once, run anywhere” Error rate grows with code base size Cross-Platform Support
  5. Real World Angular Erfahrungen von der Projektfront “Real Cross Platform”

    HTML5, CSS3 and JavaScript • Desktop: Windows, macOS, Linux, … • Mobile: iOS, Android, Windows 10 Mobile, … • Browser: Chrome, Firefox, Edge, Safari, … • Others: Nintendo DS, Refrigerator, … Cross-Platform Support
  6. Real World Angular Erfahrungen von der Projektfront Single-Page Web Apps

    Single-Page Web Applications (SPA) are the preferred model for implementing large-scale apps “Fat clients”/Rich Internet Applications Angular is an SPA framework cross-platform support out of the box Cross-Platform Support
  7. Real World Angular Erfahrungen von der Projektfront Tools Cordova (PhoneGap)

    for mobile platforms Electron for desktop platforms Cross-Platform-Support
  8. Real World Angular Erfahrungen von der Projektfront Cordova & Electron

    Cross-Platform-Support JS HTML CSS .ipa .exe .app ELF .apk .appx Single-Page Web Application Cordova Electron
  9. Real World Angular Erfahrungen von der Projektfront Handling Platform Differences

    Different APIs depending on the environment, e.g. camera access Browser/Electron: navigator.mediaDevices.getUserMedia() Cordova: navigator.camera.getPicture() Cross-Platform Support DEMO
  10. Real World Angular Erfahrungen von der Projektfront Recap Can be

    easily handled by Angular’s DI Provide base type and concrete implementations (e.g. desktop/mobile) Cross-Platform Support
  11. Real World Angular Erfahrungen von der Projektfront Recap Masquerading platform

    differences by dependency injection and polymorphism Prevents endless switch blocks, #ifdef compiler flags, … constructor(private _camera: CameraService) { } // this._camera.getPicture(); Cross-Platform Support
  12. Cross-Platform Support • Single-Page Applications • Handling Platform Differences Build

    Process • Angular CLI • Custom Build Bundling • Ahead of Time Compilation • Tree Shaking Performance • Change Detection Strategies • NgZone Real World Angular Erfahrungen von der Projektfront
  13. Real World Angular Erfahrungen von der Projektfront The Problem Web

    application development is getting more complex Usage of source-to-source compilers like TypeScript, LESS, … Fast and easy development and production We need a build process! Build Process
  14. Real World Angular Erfahrungen von der Projektfront Angular CLI >

    npm install -g @angular/cli > ng new my-app --ng4 Build Process
  15. Real World Angular Erfahrungen von der Projektfront Angular CLI Usage

    Bootstrapping • ng new project Scaffolding • ng generate component foo Build process • ng build Development server • ng serve Build Process
  16. Real World Angular Erfahrungen von der Projektfront Angular CLI Advantages

    Extremely easy and fast setup No configuration E2E and unit test support A good starting point for • learning Angular basics • seeing quick results (generalized use cases, private projects) Build Process
  17. Real World Angular Erfahrungen von der Projektfront Angular CLI Drawbacks

    Differs from Angular’s QuickStart and core documentation by using Webpack instead of SystemJS Opinionated directory structure/naming “One size fits all” build process Hardly extensible/configurable (as of beta) Build Process
  18. Real World Angular Erfahrungen von der Projektfront Angular CLI Eject

    ng eject since 1.0.0-beta.32 “Ejects” Webpack configuration and build scripts to project scope ng build => npm run build Problem: build scripts are getting stale Build Process
  19. Real World Angular Erfahrungen von der Projektfront Angular CLI vs.

    Custom Build Custom (delta) builds can unleash faster development speed compared to Angular CLI e.g. based on Gulp (or ejected Angular CLI build) More flexibility (e.g. 2+ repositories) Tailored to the customer’s needs Thinktecture customer projects using Angular CLI: 0 Setting up a custom-tailored build process can take a considerable amount of time Build Process
  20. gulp.task('prod:bundle', done => { return rollup({ entry: './build/aot/src/app/main.aot.js', format: 'iife',

    plugins: [ nodeResolve({ jsnext: true, module: true }), commonjs(), uglify() ] }) .pipe(source('app.js')) .pipe(gulp.dest(config.prod.target)) }); Real World Angular Erfahrungen von der Projektfront Build Process Custom Gulp Build Step Sample
  21. Cross-Platform Support • Single-Page Applications • Handling Platform Differences Build

    Process • Angular CLI • Custom Build Bundling • Ahead of Time Compilation • Tree Shaking Performance • Change Detection Strategies • NgZone Real World Angular Erfahrungen von der Projektfront
  22. Real World Angular Erfahrungen von der Projektfront The Problem Angular’s

    development directory structure is hard to • deploy • serve • cache • … Lots of files, lots of requests Angular and its dependencies are large in size, apps use only a fragment Bundling
  23. Real World Angular Erfahrungen von der Projektfront The Problem Just-in-Time

    compilation (JiT) • Slow, client-side rendering • Compiler is 1.2 MB large in size • Template errors detected at runtime only • Potentially dangerous (injection attacks) Bundling
  24. Real World Angular Erfahrungen von der Projektfront The Problem Goal:

    Angular app • with all components pre-compiled • combined in a single file • without redundant/unused code • uglified, compressed Bundling
  25. Real World Angular Erfahrungen von der Projektfront Measures Ahead-of-Time (AoT)

    compilation • “XAML to BAML” Bundling • Tree Shaking • Uglify • Compress • … Bundling
  26. Real World Angular Erfahrungen von der Projektfront Status Quo Angular

    Quickstart & CLI use Just in Time (JiT) compilation per default Angular CLI provides AoT & production build out of the box AoT requires some additional steps Pre-compiling the application using the (offline) Angular compiler ngc A different Angular runtime platform has to be used Bundling
  27. Real World Angular Erfahrungen von der Projektfront Platforms & Renderers

    Angular is platform-independent, i.e. Angular-based apps can run outside of the browser • AngularJS: hides information in DOM Angular provides support for custom renderers Bundling
  28. Real World Angular Erfahrungen von der Projektfront Platforms platformBrowserDynamic •

    JiT platformBrowser • AoT • only pre-rendered component factories exist • ngc is executed before deployment Bundling
  29. Real World Angular Erfahrungen von der Projektfront Platforms platformServer •

    Server-Side Rendering (Angular Universal) platformNativeScriptDynamic • Building native apps with Angular platformWorkerApp • Render in Web Worker (background thread) Bundling
  30. Real World Angular Erfahrungen von der Projektfront Angular Compilation Bundling

    https://www.youtube.com/watch?v=kW9cJsvcsGo Component @Component({ … }) class UserComponent { user = { name: 'Chris' }; } Template <div>hello {{ user.name }}</div> View Class var v = this.comp.user.name;
  31. Real World Angular Erfahrungen von der Projektfront Bundling JiT Compilation

    Component @Component({ … }) class UserComponent { user = { name: 'Chris' }; } Template <div>hello {{ user.name }}</div> Server Client Component @Component({ … }) class UserComponent { user = { name: 'Chris' }; } Template <div>hello {{ user.name }}</div> View Class var v = this.comp.user.name;
  32. Real World Angular Erfahrungen von der Projektfront Bundling AoT Compilation

    Component @Component({ … }) class UserComponent { user = { name: 'Chris' }; } Template <div>hello {{ user.name }}</div> Server Client Component @Component({ … }) class UserComponent { user = { name: 'Chris' }; } View Class var v = this.comp.user.name; Template <div>hello {{ user.name }}</div> View Class var v = this.comp.user.name;
  33. Real World Angular Erfahrungen von der Projektfront Tree Shaking “A

    Tree Shaker walks the dependency graph, top to bottom, and shakes out unused code like dead needles in a Christmas tree.” • https://angular.io/docs/ts/latest/cookbook/aot-compiler.html Bundling
  34. !function(){ var obj = { foo: function () { //

    Hi there! }, bar: function () { this.baz(); }, baz: function () { // stub } }; obj.foo(); }(); Real World Angular Erfahrungen von der Projektfront Bundling Tree Shaking Principle
  35. Real World Angular Erfahrungen von der Projektfront How To Webpack

    (e.g. Angular CLI build) SystemJS & Rollup Bundling DEMO
  36. Real World Angular Erfahrungen von der Projektfront Recap ng new

    demo-app --ng4 ng build --dev // no tree shaking, JiT ng build --aot // no tree shaking, AoT ng build --prod --aot // tree shaking, AoT Bundling
  37. Real World Angular Erfahrungen von der Projektfront A Simple Demo

    App Dev build: 3.0 MB (without source maps) AoT build: 1.6 MB (without source maps) AoT+TreeShake: 880K (220K gzipped) Bundling
  38. Real World Angular Erfahrungen von der Projektfront A Simple Demo

    App JiT build: ~650 ms AoT build: ~300 ms Mid 2015 MacBook Pro, served locally a few test runs, results may & will vary Bundling
  39. Real World Angular Erfahrungen von der Projektfront AoT Drawbacks Dynamic

    template compilation via ComponentFactoryResolver is discouraged in combination with AoT COMPILER_PROVIDERS are unavailable • https://github.com/angular/angular/issues/11780 Bundling
  40. Real World Angular Erfahrungen von der Projektfront SystemJS/Rollup Drawbacks Rollup

    does not support chunks • i.e. it can only create one single output file Tree Shaking with Rollup removes ability to lazy load SystemJS packages • Lazy Loading isn’t possible Bundling
  41. Cross-Platform Support • Single-Page Applications • Handling Platform Differences Build

    Process • Angular CLI • Custom Build Bundling • Ahead of Time Compilation • Tree Shaking Performance • Change Detection Strategies • NgZone Real World Angular Erfahrungen von der Projektfront
  42. Real World Angular Erfahrungen von der Projektfront Single-Page Web App

    Performance Data Flow Component Communication Change Detection Performance
  43. Real World Angular Erfahrungen von der Projektfront Angular Performance Uni-directional

    data flow (exclusively) Prevents change detection cycles • AngularJS: 10 $digest() iterations reached “Virtual” two-way binding in Angular by combining property/event bindings • Banana in a box/compiler magic: [(ngModel)] Performance
  44. Real World Angular Erfahrungen von der Projektfront Change Detection Strategies

    <my-component [foo]="bar"> </my-component> @Component({ selector: 'my-component', template: '{{ foo }}', changeDetection: ChangeDetectionStrategy.OnPush }) export class MyComponent { @Input() public foo: string; } Components can restrict change detection to changes of @Input parameters (OnPush) Immutables are required, otherwise model and view can get out of sync Performance
  45. Real World Angular Erfahrungen von der Projektfront Change Detection Strategies

    ChangeDetectionStrategy.Default Magically checks for changes and updates bindings accordingly But how? Performance
  46. Real World Angular Erfahrungen von der Projektfront A look at

    Angular’s dependencies "dependencies": { "@angular/common": "~2.4.0", "angular-in-memory-web-api": "~0.2.4", "systemjs": "0.19.40", "core-js": "^2.4.1", "rxjs": "5.0.1", "zone.js": "^0.7.4" }, Performance
  47. Real World Angular Erfahrungen von der Projektfront Zone.js Provided by

    the Angular team • https://github.com/angular/zone.js Provides an execution context for asynchronous JavaScript A meta-monkey patch Performance
  48. Real World Angular Erfahrungen von der Projektfront Execution Context function

    main() { // const start = performance.now(); a(); setTimeout(b, 0); c(); // const stop = performance.now(); // const ms = stop - start; } Performance
  49. Real World Angular Erfahrungen von der Projektfront Zone.js Oversimplified Zone.run(main);

    onZoneEnter(); function main() { a(); setTimeout(b, 0); c(); } onZoneLeave(); Performance const orig = window.setTimeout; window.setTimeout = (c, t) => { orig(() => { onZoneEnter(); c(); onZoneLeave(); }, t); };
  50. Real World Angular Erfahrungen von der Projektfront Performance A Meta-Monkey

    Patch setTimeout setInterval geolocation.getCurrentPosition XMLHttpRequest PromiseRejectionEvent requestAnimationFrame click focus mousemove addEventListener
  51. Real World Angular Erfahrungen von der Projektfront Zone.js Angular’s change

    detection is based on Zone.js • AngularJS digest cycle: $timeout, $apply() Angular is running inside an own zone, referred to as the NgZone Performance
  52. Real World Angular Erfahrungen von der Projektfront The Problem Boxes,

    draggable around the screen Component requires “default” change detection (i.e. it can’t rely on input changes) Dragging performance drops drastically with an increasing number of boxes Performance DEMO
  53. Real World Angular Erfahrungen von der Projektfront Performance NgZone current

    (global) zone NgZone mousemove Detect changes mousemove Detect changes mousemove Detect changes mousemove Detect changes
  54. Real World Angular Erfahrungen von der Projektfront Running Outside Angular

    constructor (ngZone: NgZone) { ngZone.runOutsideAngular(() => { // runs outside Angular zone ngZone.run(() => { // runs inside Angular zone }); }); } Performance
  55. Real World Angular Erfahrungen von der Projektfront The Fix Run

    performance-critical code outside Angular Setting the box location directly via Renderer & ElementRef.nativeElement Performance
  56. Real World Angular Erfahrungen von der Projektfront The Fix Use

    of Renderer is crucial to stay platform independent elementRef.nativeElement.style.left = "3px"; renderer.setElementStyle(elementRef.nativeElement, "left", "3px"); Performance DEMO
  57. Real World Angular Erfahrungen von der Projektfront Performance NgZone current

    (global) zone NgZone mousemove mousemove mousemove mousemove
  58. Real World Angular Erfahrungen von der Projektfront The Fix In

    particular, this has also helped fixing Protractor timeouts when long- running asynchronous tasks are launched on application startup • https://christianliebel.com/2016/11/angular-2-protractor-timeout- heres-fix/ Performance
  59. Cross-Platform Support • Single-Page Applications • Handling Platform Differences Build

    Process • Angular CLI • Custom Build Bundling • Ahead of Time Compilation • Tree Shaking Performance • Change Detection Strategies • NgZone Real World Angular Erfahrungen von der Projektfront