1
|
import 'zone.js/dist/zone-node';
|
2
|
import 'reflect-metadata';
|
3
|
import { renderModuleFactory } from '@angular/platform-server';
|
4
|
import { enableProdMode } from '@angular/core';
|
5
|
|
6
|
import * as express from 'express';
|
7
|
import { join } from 'path';
|
8
|
import { readFileSync } from 'fs';
|
9
|
|
10
|
// Faster server renders w/ Prod mode (dev mode never needed)
|
11
|
enableProdMode();
|
12
|
|
13
|
// Express server
|
14
|
const app = express();
|
15
|
|
16
|
const PORT = 4000;
|
17
|
const DIST_FOLDER = join(process.cwd(), 'dist');
|
18
|
|
19
|
// Our index.html we'll use as our template
|
20
|
const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();
|
21
|
|
22
|
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
|
23
|
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require('./dist/server/main');
|
24
|
|
25
|
// Express Engine
|
26
|
import {ngExpressEngine, RenderOptions} from '@nguniversal/express-engine';
|
27
|
// Import module map for lazy loading
|
28
|
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
|
29
|
import {REQUEST, RESPONSE} from "@nguniversal/express-engine/tokens";
|
30
|
|
31
|
// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
|
32
|
// app.engine('html', ngExpressEngine({
|
33
|
// bootstrap: AppServerModuleNgFactory,
|
34
|
// providers: [
|
35
|
// { provide: 'request', useFactory: () => options.req, deps: [] },
|
36
|
// provideModuleMap(LAZY_MODULE_MAP)
|
37
|
// ]
|
38
|
// }));
|
39
|
|
40
|
// be able to get request and get domain from there
|
41
|
app.engine('html', (_, options: any, callback) => {
|
42
|
const opts = {
|
43
|
document: template,
|
44
|
url: options.req.url,
|
45
|
extraProviders: [
|
46
|
provideModuleMap(LAZY_MODULE_MAP),
|
47
|
{
|
48
|
provide: REQUEST,
|
49
|
useValue: options.req
|
50
|
},
|
51
|
{
|
52
|
provide: RESPONSE,
|
53
|
useValue: options.req.res,
|
54
|
},
|
55
|
]
|
56
|
};
|
57
|
|
58
|
renderModuleFactory(AppServerModuleNgFactory, opts)
|
59
|
.then(html => callback(null, html)
|
60
|
);
|
61
|
});
|
62
|
app.set('view engine', 'html');
|
63
|
app.set('views', join(DIST_FOLDER, 'browser'));
|
64
|
|
65
|
/* - Example Express Rest API endpoints -
|
66
|
app.get('/api/**', (req, res) => { });
|
67
|
*/
|
68
|
|
69
|
// Server static files from /browser
|
70
|
app.get('*.*', express.static(join(DIST_FOLDER, 'browser'), {
|
71
|
maxAge: '1y'
|
72
|
}));
|
73
|
|
74
|
// ALl regular routes use the Universal engine
|
75
|
app.get('*', (req, res) => {
|
76
|
res.render('index', { req });
|
77
|
});
|
78
|
|
79
|
// Start up the Node server
|
80
|
app.listen(PORT, () => {
|
81
|
console.log(`Node Express server listening on http://localhost:${PORT}`);
|
82
|
});
|