Server-Side Rendering
npm install
npm start
to build your client app and start a web servernpm run build
to prepare a distributable bundle
- run
npm start
andnpm run watch
in two separate terminals to build your client app, start a web server, and allow file changes to update in realtime
When building Universal components in Angular 2 there are a few things to keep in mind.
- To use
templateUrl
orstyleUrls
you must useangular2-template-loader
in your TS loaders.- This is already setup within this starter repo. Look at the webpack.config file here for details & implementation.
window
,document
,navigator
, and other browser types - do not exist on the server - so using them, or any library that uses them (jQuery for example) will not work. You do have some options, if you truly need some of this functionality:- If you need to use them, consider limiting them to only your main.client and wrapping them situationally with the imported isBrowser / isNode features from Universal.
import { isBrowser, isNode } from 'angular2-universal'
; - Another option is using
DOM
from "@angular/platform-browser"
- If you need to use them, consider limiting them to only your main.client and wrapping them situationally with the imported isBrowser / isNode features from Universal.
- Don't manipulate the nativeElement directly. Use the Renderer. We do this to ensure that in any environment we're able to change our view.
constructor(element: ElementRef, renderer: Renderer) {
renderer.setElementStyle(element.nativeElement, 'font-size', 'x-large');
}
- The application runs XHR requests on the server & once again on the Client-side (when the application bootstraps)
- Use a UniversalCache instead of regular Http, to save certain requests so they aren't re-ran again on the Client. (Example useage here)
- Know the difference between attributes and properties in relation to the DOM.
- Keep your directives stateless as much as possible. For stateful directives, you may need to provide an attribute that reflects the corresponding property with an initial string value such as url in img tag. For our native
<img src="">
element the src attribute is reflected as the src property of the element type HTMLImageElement.
If you have node modules with promise polyfill dependency on server - there is chance to get the following exception:
Error: Zone.js has detected that ZoneAwarePromise `(window|global).Promise` has been overwritten.
It occurs because Zone.js Promise implementation is not detected as Promise by some polyfills (e.g. es6-promise before 4.x).
To sort it out, you need such polyfills initialized before zone.js. Zone.js is initialized in 'angular2-universal-polyfills' import of server.ts. So import problematic modules before this line.