server.ts.template 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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/**', (req, res) => { });
  20. // Serve static files from /browser
  21. server.get('*.*', express.static(distFolder, {
  22. maxAge: '1y'
  23. }));
  24. // All regular routes use the Angular engine
  25. server.get('*', (req, res, next) => {
  26. const { protocol, originalUrl, baseUrl, headers } = req;
  27. commonEngine
  28. .render({
  29. <% if (isStandalone) { %>bootstrap<% } else { %>bootstrap: AppServerModule<% } %>,
  30. documentFilePath: indexHtml,
  31. url: `${protocol}://${headers.host}${originalUrl}`,
  32. publicPath: distFolder,
  33. providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
  34. })
  35. .then((html) => res.send(html))
  36. .catch((err) => next(err));
  37. });
  38. return server;
  39. }
  40. function run(): void {
  41. const port = process.env['PORT'] || 4000;
  42. // Start up the Node server
  43. const server = app();
  44. server.listen(port, () => {
  45. console.log(`Node Express server listening on http://localhost:${port}`);
  46. });
  47. }
  48. // Webpack will replace 'require' with '__webpack_require__'
  49. // '__non_webpack_require__' is a proxy to Node 'require'
  50. // The below code is to ensure that the server is run only when not requiring the bundle.
  51. declare const __non_webpack_require__: NodeRequire;
  52. const mainModule = __non_webpack_require__.main;
  53. const moduleFilename = mainModule && mainModule.filename || '';
  54. if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  55. run();
  56. }
  57. export default <% if (isStandalone) { %>bootstrap<% } else { %>AppServerModule<% } %>;