From 7df7f6152223ef84c40df625a1904a9f126e2648 Mon Sep 17 00:00:00 2001 From: "argiro.kokogiannaki" Date: Fri, 9 Dec 2016 11:09:01 +0000 Subject: [PATCH] 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 --- portal-2/README.md | 97 ++++++++++++++++++++++++--------- portal-2/package.json | 7 +++ portal-2/src/browser.module.ts | 4 +- portal-2/src/client.aot.ts | 11 +--- portal-2/src/client.ts | 11 +--- portal-2/src/server.aot.ts | 6 +- portal-2/webpack.prod.config.ts | 8 +-- 7 files changed, 90 insertions(+), 54 deletions(-) diff --git a/portal-2/README.md b/portal-2/README.md index 7c4cf261..bb1ab316 100644 --- a/portal-2/README.md +++ b/portal-2/README.md @@ -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) -## 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 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 @@ -59,6 +33,77 @@ constructor(element: ElementRef, renderer: Renderer) { ## AoT and 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 `` 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 If you have node modules with promise polyfill dependency on server - there is chance to get the following exception: diff --git a/portal-2/package.json b/portal-2/package.json index 1b7b4ff6..adc7c4fd 100644 --- a/portal-2/package.json +++ b/portal-2/package.json @@ -19,6 +19,8 @@ "build:prod:json": "webpack --config webpack.prod.config.ts --json | webpack-bundle-size-analyzer", "ngc": "ngc -p tsconfig.aot.json", "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", "debug:server": "node-nightly --inspect --debug-brk dist/server/index.js", "start": "npm run server", @@ -48,6 +50,8 @@ "@angular/platform-server": "~2.1.2", "@angular/router": "~3.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-platform-node": "~2.1.0-rc.1", "angular2-universal": "~2.1.0-rc.1", @@ -71,6 +75,7 @@ "@types/express": "^4.0.32", "@types/express-serve-static-core": "^4.0.33", "@types/hammerjs": "^2.0.32", + "@types/memory-cache": "0.0.29", "@types/mime": "0.0.28", "@types/node": "^6.0.38", "@types/serve-static": "^1.7.27", @@ -84,6 +89,7 @@ "iltorb": "^1.0.13", "imports-loader": "^0.6.5", "json-loader": "^0.5.4", + "memory-cache": "^0.1.6", "nodemon": "^1.10.0", "raw-loader": "^0.5.1", "reflect-metadata": "0.1.8", @@ -92,6 +98,7 @@ "ts-helpers": "^1.1.2", "ts-node": "^1.3.0", "typescript": "2.0.2", + "uglify-js" : "^2.7.4", "v8-lazy-parse-webpack-plugin": "^0.3.0", "webpack": "2.1.0-beta.27", "webpack-bundle-analyzer": "1.4.1", diff --git a/portal-2/src/browser.module.ts b/portal-2/src/browser.module.ts index 283ea80d..512e6895 100755 --- a/portal-2/src/browser.module.ts +++ b/portal-2/src/browser.module.ts @@ -2,6 +2,7 @@ import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; 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 { IdlePreload, IdlePreloadModule } from '@angularclass/idle-preload'; import { AppModule, AppComponent } from './app/app.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 FormsModule, - RouterModule.forRoot([], { useHash: false }), + RouterModule.forRoot([], { useHash: false, preloadingStrategy: IdlePreload }), + IdlePreloadModule.forRoot(), SharedModule.forRoot(), AppModule, ], diff --git a/portal-2/src/client.aot.ts b/portal-2/src/client.aot.ts index 7f5a6a41..a04f2950 100644 --- a/portal-2/src/client.aot.ts +++ b/portal-2/src/client.aot.ts @@ -6,6 +6,7 @@ import './__workaround.browser'; // temporary until 2.1.1 things are patched in // Angular 2 import { enableProdMode } from '@angular/core'; import { platformBrowser } from '@angular/platform-browser'; +import { bootloader } from '@angularclass/bootloader'; // for AoT use platformBrowser // import { platformUniversalDynamic } from 'angular2-universal/browser'; @@ -32,12 +33,4 @@ export function main() { } // support async tag or hmr -switch (document.readyState) { - case 'loading': - document.addEventListener('DOMContentLoaded', () => main()); - break; - case 'interactive': - case 'complete': - default: - main(); -} +bootloader(main); diff --git a/portal-2/src/client.ts b/portal-2/src/client.ts index 90161c45..d4c5a8ce 100644 --- a/portal-2/src/client.ts +++ b/portal-2/src/client.ts @@ -6,6 +6,7 @@ import './__workaround.browser'; // temporary until 2.1.1 things are patched in // Angular 2 import { enableProdMode } from '@angular/core'; import { platformUniversalDynamic } from 'angular2-universal/browser'; +import { bootloader } from '@angularclass/bootloader'; import { load as loadWebFont } from 'webfontloader'; @@ -30,12 +31,4 @@ export function main() { } // support async tag or hmr -switch (document.readyState) { - case 'loading': - document.addEventListener('DOMContentLoaded', () => main()); - break; - case 'interactive': - case 'complete': - default: - main(); -} +bootloader(main); diff --git a/portal-2/src/server.aot.ts b/portal-2/src/server.aot.ts index 0c8f95ba..d643c819 100644 --- a/portal-2/src/server.aot.ts +++ b/portal-2/src/server.aot.ts @@ -12,11 +12,7 @@ import * as express from 'express'; import * as bodyParser from 'body-parser'; import * as cookieParser from 'cookie-parser'; import * as morgan from 'morgan'; - -const { gzipSync } = require('zlib'); -const accepts = require('accepts'); -const { compressSync } = require('iltorb'); -const interceptor = require('express-interceptor'); +import * as compression from 'compression'; // Angular 2 import { enableProdMode } from '@angular/core'; diff --git a/portal-2/webpack.prod.config.ts b/portal-2/webpack.prod.config.ts index a0f1b663..40aec8ad 100644 --- a/portal-2/webpack.prod.config.ts +++ b/portal-2/webpack.prod.config.ts @@ -12,10 +12,10 @@ export const commonPlugins = [ new V8LazyParseWebpackPlugin(), new webpack.DefinePlugin({ - 'process.env': { - 'NODE_ENV': JSON.stringify('production'), - 'AOT': true - } + // do not use an object for 'process.env' otherwise all other environment + // variables are set to 'undefined' see issue #291 + 'process.env.NODE_ENV': JSON.stringify('production'), + 'process.env.AOT': true }), // Loader options