Bootstrapping Angular Universal App
Show the necessary server-side code to bootstrap an Angular Universal application using Express.js.
import * as express from 'express';
import { join } from 'path';
// These are important and needed before anything else
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { ngExpressEngine } from '@nguniversal/express-engine';
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
import { AppServerModuleNgFactory, LAZY_MODULE_MAP } from './dist/server/main';
const app = express();
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist');
// Set the engine
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', join(DIST_FOLDER, 'browser'));
// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser'), {
maxAge: '1y'
}));
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render('index', { req });
});
app.listen(PORT, () => {
console.log(`Node Express server listening on http://localhost:${PORT}`);
});
This code imports the necessary modules and sets up an Express server to handle requests. It configures Angular Universal with the 'ngExpressEngine' for server-side rendering of Angular applications. It specifies where the server views are located and serves static files from the 'browser' directory. All other routes are handled by Angular Universal. The application listens on the specified port.