Update to the lattest angular universal-starter project

git-svn-id: https://svn.driver.research-infrastructures.eu/driver/dnet40/modules/uoa-services-portal/trunk@44883 d315682c-612b-4755-9ff5-7f18f6832af3
This commit is contained in:
argiro.kokogiannaki 2016-12-09 11:09:01 +00:00
parent 80dda369cb
commit 7df7f61522
7 changed files with 90 additions and 54 deletions

View File

@ -14,32 +14,6 @@ A minimal Angular 2 starter for Universal JavaScript using TypeScript 2 and Webp
[![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy) [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy)
## Universal "Gotchas"
> When building Universal components in Angular 2 there are a few things to keep in mind.
- To use `templateUrl` or `styleUrls` you must use **`angular2-template-loader`** in your TS loaders.
- This is already setup within this starter repo. Look at the webpack.config file [here](https://github.com/angular/universal-starter/blob/master/webpack.config.ts) 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"](https://github.com/angular/angular/blob/e3687706c71beb7c9dbdae1bbb5fbbcea588c476/modules/%40angular/platform-browser/src/dom/dom_adapter.ts#L34)
- **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](https://github.com/angular/universal-starter/blob/master/src/app/shared/api.service.ts#L47-L71) instead of regular Http, to save certain requests so they aren't re-ran again on the Client.
- 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.
## Upcoming Universal features
- SeoServices
- Universal fixes for Angular Core 2.1.1
## Installation ## Installation
@ -59,6 +33,77 @@ constructor(element: ElementRef, renderer: Renderer) {
## AoT and Prod ## AoT and Prod
* `npm run build:prod:ngc` to compile the ngfactory files and build prod * `npm run build:prod:ngc` to compile the ngfactory files and build prod
## Universal "Gotchas"
> When building Universal components in Angular 2 there are a few things to keep in mind.
- To use `templateUrl` or `styleUrls` you must use **`angular2-template-loader`** in your TS loaders.
- This is already setup within this starter repo. Look at the webpack.config file [here](https://github.com/angular/universal-starter/blob/master/webpack.config.ts) 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"](https://github.com/angular/angular/blob/e3687706c71beb7c9dbdae1bbb5fbbcea588c476/modules/%40angular/platform-browser/src/dom/dom_adapter.ts#L34)
- **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](https://github.com/angular/universal-starter/blob/master/src/+app/shared/api.service.ts#L47-L71) instead of regular Http, to save certain requests so they aren't re-ran again on the Client.
- 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.
### Brotli Compression Support
To enable Brotli compression for server response with fallback for gzip replace the following code from src/server.aot.ts
```
import * as compression from 'compression';
app.use(compression());
```
with
```
import * as mcache from 'memory-cache';
const { gzipSync } = require('zlib');
const accepts = require('accepts');
const { compressSync } = require('iltorb');
const interceptor = require('express-interceptor');
app.use(interceptor((req, res)=>({
// don't compress responses with this request header
isInterceptable: () => (!req.headers['x-no-compression']),
intercept: ( body, send ) => {
const encodings = new Set(accepts(req).encodings());
const bodyBuffer = new Buffer(body);
// url specific key for response cache
const key = '__response__' + req.originalUrl || req.url;
let output = bodyBuffer;
// check if cache exists
if (mcache.get(key) === null) {
// check for encoding support
if (encodings.has('br')) {
// brotli
res.setHeader('Content-Encoding', 'br');
output = compressSync(bodyBuffer);
mcache.put(key, {output, encoding: 'br'});
} else if (encodings.has('gzip')) {
// gzip
res.setHeader('Content-Encoding', 'gzip');
output = gzipSync(bodyBuffer);
mcache.put(key, {output, encoding: 'gzip'});
}
} else {
const { output, encoding } = mcache.get(key);
res.setHeader('Content-Encoding', encoding);
send(output);
}
send(output);
}
})));
```
this will check the support, compress and cache the response.
## Edge case of server compatibility with Promise polyfills ## Edge case of server compatibility with Promise polyfills
If you have node modules with promise polyfill dependency on server - there is chance to get the following exception: If you have node modules with promise polyfill dependency on server - there is chance to get the following exception:

View File

@ -19,6 +19,8 @@
"build:prod:json": "webpack --config webpack.prod.config.ts --json | webpack-bundle-size-analyzer", "build:prod:json": "webpack --config webpack.prod.config.ts --json | webpack-bundle-size-analyzer",
"ngc": "ngc -p tsconfig.aot.json", "ngc": "ngc -p tsconfig.aot.json",
"prestart": "npm run build", "prestart": "npm run build",
"minify": "uglifyjs dist/client/main.bundle.js --screw-ie8 --compress --mangle --output dist/client/main.bundle.min.js",
"minify-test": "uglifyjs dist/client/main.js --screw-ie8 --compress --mangle --output dist/client/main.xmin.js",
"server": "nodemon dist/server/index.js", "server": "nodemon dist/server/index.js",
"debug:server": "node-nightly --inspect --debug-brk dist/server/index.js", "debug:server": "node-nightly --inspect --debug-brk dist/server/index.js",
"start": "npm run server", "start": "npm run server",
@ -48,6 +50,8 @@
"@angular/platform-server": "~2.1.2", "@angular/platform-server": "~2.1.2",
"@angular/router": "~3.1.2", "@angular/router": "~3.1.2",
"@angular/upgrade": "~2.1.2", "@angular/upgrade": "~2.1.2",
"@angularclass/bootloader": "~1.0.1",
"@angularclass/idle-preload": "~1.0.4",
"angular2-express-engine": "~2.1.0-rc.1", "angular2-express-engine": "~2.1.0-rc.1",
"angular2-platform-node": "~2.1.0-rc.1", "angular2-platform-node": "~2.1.0-rc.1",
"angular2-universal": "~2.1.0-rc.1", "angular2-universal": "~2.1.0-rc.1",
@ -71,6 +75,7 @@
"@types/express": "^4.0.32", "@types/express": "^4.0.32",
"@types/express-serve-static-core": "^4.0.33", "@types/express-serve-static-core": "^4.0.33",
"@types/hammerjs": "^2.0.32", "@types/hammerjs": "^2.0.32",
"@types/memory-cache": "0.0.29",
"@types/mime": "0.0.28", "@types/mime": "0.0.28",
"@types/node": "^6.0.38", "@types/node": "^6.0.38",
"@types/serve-static": "^1.7.27", "@types/serve-static": "^1.7.27",
@ -84,6 +89,7 @@
"iltorb": "^1.0.13", "iltorb": "^1.0.13",
"imports-loader": "^0.6.5", "imports-loader": "^0.6.5",
"json-loader": "^0.5.4", "json-loader": "^0.5.4",
"memory-cache": "^0.1.6",
"nodemon": "^1.10.0", "nodemon": "^1.10.0",
"raw-loader": "^0.5.1", "raw-loader": "^0.5.1",
"reflect-metadata": "0.1.8", "reflect-metadata": "0.1.8",
@ -92,6 +98,7 @@
"ts-helpers": "^1.1.2", "ts-helpers": "^1.1.2",
"ts-node": "^1.3.0", "ts-node": "^1.3.0",
"typescript": "2.0.2", "typescript": "2.0.2",
"uglify-js" : "^2.7.4",
"v8-lazy-parse-webpack-plugin": "^0.3.0", "v8-lazy-parse-webpack-plugin": "^0.3.0",
"webpack": "2.1.0-beta.27", "webpack": "2.1.0-beta.27",
"webpack-bundle-analyzer": "1.4.1", "webpack-bundle-analyzer": "1.4.1",

View File

@ -2,6 +2,7 @@ import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router'; import { RouterModule } from '@angular/router';
import { UniversalModule, isBrowser, isNode, AUTO_PREBOOT } from 'angular2-universal/browser'; // for AoT we need to manually split universal packages import { UniversalModule, isBrowser, isNode, AUTO_PREBOOT } from 'angular2-universal/browser'; // for AoT we need to manually split universal packages
import { IdlePreload, IdlePreloadModule } from '@angularclass/idle-preload';
import { AppModule, AppComponent } from './app/app.module'; import { AppModule, AppComponent } from './app/app.module';
import { SharedModule } from './app/shared/shared.module'; import { SharedModule } from './app/shared/shared.module';
@ -38,8 +39,9 @@ export const UNIVERSAL_KEY = 'UNIVERSAL_CACHE';
UniversalModule, // BrowserModule, HttpModule, and JsonpModule are included UniversalModule, // BrowserModule, HttpModule, and JsonpModule are included
FormsModule, FormsModule,
RouterModule.forRoot([], { useHash: false }), RouterModule.forRoot([], { useHash: false, preloadingStrategy: IdlePreload }),
IdlePreloadModule.forRoot(),
SharedModule.forRoot(), SharedModule.forRoot(),
AppModule, AppModule,
], ],

View File

@ -6,6 +6,7 @@ import './__workaround.browser'; // temporary until 2.1.1 things are patched in
// Angular 2 // Angular 2
import { enableProdMode } from '@angular/core'; import { enableProdMode } from '@angular/core';
import { platformBrowser } from '@angular/platform-browser'; import { platformBrowser } from '@angular/platform-browser';
import { bootloader } from '@angularclass/bootloader';
// for AoT use platformBrowser // for AoT use platformBrowser
// import { platformUniversalDynamic } from 'angular2-universal/browser'; // import { platformUniversalDynamic } from 'angular2-universal/browser';
@ -32,12 +33,4 @@ export function main() {
} }
// support async tag or hmr // support async tag or hmr
switch (document.readyState) { bootloader(main);
case 'loading':
document.addEventListener('DOMContentLoaded', () => main());
break;
case 'interactive':
case 'complete':
default:
main();
}

View File

@ -6,6 +6,7 @@ import './__workaround.browser'; // temporary until 2.1.1 things are patched in
// Angular 2 // Angular 2
import { enableProdMode } from '@angular/core'; import { enableProdMode } from '@angular/core';
import { platformUniversalDynamic } from 'angular2-universal/browser'; import { platformUniversalDynamic } from 'angular2-universal/browser';
import { bootloader } from '@angularclass/bootloader';
import { load as loadWebFont } from 'webfontloader'; import { load as loadWebFont } from 'webfontloader';
@ -30,12 +31,4 @@ export function main() {
} }
// support async tag or hmr // support async tag or hmr
switch (document.readyState) { bootloader(main);
case 'loading':
document.addEventListener('DOMContentLoaded', () => main());
break;
case 'interactive':
case 'complete':
default:
main();
}

View File

@ -12,11 +12,7 @@ import * as express from 'express';
import * as bodyParser from 'body-parser'; import * as bodyParser from 'body-parser';
import * as cookieParser from 'cookie-parser'; import * as cookieParser from 'cookie-parser';
import * as morgan from 'morgan'; import * as morgan from 'morgan';
import * as compression from 'compression';
const { gzipSync } = require('zlib');
const accepts = require('accepts');
const { compressSync } = require('iltorb');
const interceptor = require('express-interceptor');
// Angular 2 // Angular 2
import { enableProdMode } from '@angular/core'; import { enableProdMode } from '@angular/core';

View File

@ -12,10 +12,10 @@ export const commonPlugins = [
new V8LazyParseWebpackPlugin(), new V8LazyParseWebpackPlugin(),
new webpack.DefinePlugin({ new webpack.DefinePlugin({
'process.env': { // do not use an object for 'process.env' otherwise all other environment
'NODE_ENV': JSON.stringify('production'), // variables are set to 'undefined' see issue #291
'AOT': true 'process.env.NODE_ENV': JSON.stringify('production'),
} 'process.env.AOT': true
}), }),
// Loader options // Loader options