server.ts.template 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import 'zone.js/node';
  2. import { APP_BASE_HREF } from '@angular/common';
  3. import { CommonEngine } from '@angular/ssr/node';
  4. import express from 'express';
  5. import { existsSync } from 'node:fs';
  6. import { join } from 'node:path';
  7. import <% if (isStandalone) { %>bootstrap<% } else { %>AppServerModule<% } %> from './main.server';
  8. // The Express app is exported so that it can be used by serverless Functions.
  9. export function app(): express.Express {
  10. const server = express();
  11. const distFolder = join(process.cwd(), '<%= browserDistDirectory %>');
  12. const indexHtml = existsSync(join(distFolder, 'index.original.html'))
  13. ? join(distFolder, 'index.original.html')
  14. : join(distFolder, 'index.html');
  15. const commonEngine = new CommonEngine();
  16. server.set('view engine', 'html');
  17. server.set('views', distFolder);
  18. // Example Express Rest API endpoints
  19. // server.get('/api/{*splat}', (req, res) => { });
  20. // Serve static files from /browser
  21. server.use(express.static(distFolder, {
  22. maxAge: '1y',
  23. index: false,
  24. }));
  25. // All regular routes use the Angular engine
  26. server.use((req, res, next) => {
  27. const { protocol, originalUrl, baseUrl, headers } = req;
  28. commonEngine
  29. .render({
  30. <% if (isStandalone) { %>bootstrap<% } else { %>bootstrap: AppServerModule<% } %>,
  31. documentFilePath: indexHtml,
  32. url: `${protocol}://${headers.host}${originalUrl}`,
  33. publicPath: distFolder,
  34. providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
  35. })
  36. .then((html) => res.send(html))
  37. .catch((err) => next(err));
  38. });
  39. return server;
  40. }
  41. function run(): void {
  42. const port = process.env['PORT'] || 4000;
  43. // Start up the Node server
  44. const server = app();
  45. server.listen(port, (error) => {
  46. if (error) {
  47. throw error;
  48. }
  49. console.log(`Node Express server listening on http://localhost:${port}`);
  50. });
  51. }
  52. // Webpack will replace 'require' with '__webpack_require__'
  53. // '__non_webpack_require__' is a proxy to Node 'require'
  54. // The below code is to ensure that the server is run only when not requiring the bundle.
  55. declare const __non_webpack_require__: NodeRequire;
  56. const mainModule = __non_webpack_require__.main;
  57. const moduleFilename = mainModule && mainModule.filename || '';
  58. if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  59. run();
  60. }
  61. export default <% if (isStandalone) { %>bootstrap<% } else { %>AppServerModule<% } %>;