服务端渲染

本指南假设你已了解关于 Angular Universal:服务端渲染 的相关知识。

本指南 Web 服务器是基于常见的 Express 框架。

安装依赖

  1. $ ng add @nguniversal/express-engine --clientProject <project-name>

修改服务端根模块

app.server.module.ts

  1. import { NgModule } from '@angular/core';
  2. import { ServerModule } from '@angular/platform-server';
  3. import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';
  4. import { AppModule } from './app.module';
  5. import { AppComponent } from './app.component';
  6. // 引入必要的模块
  7. import { NoopAnimationsModule } from '@angular/platform-browser/animations';
  8. import { HttpClientModule } from '@angular/common/http';
  9. import { en_US, NZ_I18N, NzI18nModule } from 'ng-zorro-antd/i18n';
  10. @NgModule({
  11. imports: [
  12. AppModule,
  13. ServerModule,
  14. ModuleMapLoaderModule,
  15. HttpClientModule,
  16. NoopAnimationsModule,
  17. NzI18nModule
  18. ],
  19. bootstrap: [AppComponent],
  20. providers: [
  21. { provide: NZ_I18N, useValue: en_US }
  22. ]
  23. })
  24. export class AppServerModule {}

修改服务器环境

server.ts

  1. import 'zone.js/dist/zone-node';
  2. import {enableProdMode} from '@angular/core';
  3. // Express Engine
  4. import {ngExpressEngine} from '@nguniversal/express-engine';
  5. // Import module map for lazy loading
  6. import {provideModuleMap} from '@nguniversal/module-map-ngfactory-loader';
  7. import * as express from 'express';
  8. import {join} from 'path';
  9. // Faster server renders w/ Prod mode (dev mode never needed)
  10. enableProdMode();
  11. // 修复 `Event is not defined` 的错误 https://github.com/angular/universal/issues/844
  12. global['Event'] = null;
  13. // Express server
  14. const app = express();
  15. const PORT = process.env.PORT || 4000;
  16. const DIST_FOLDER = join(process.cwd(), 'dist/browser');
  17. // * NOTE :: leave this as require() since this file is built Dynamically from webpack
  18. const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main');
  19. // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  20. app.engine('html', ngExpressEngine({
  21. bootstrap: AppServerModuleNgFactory,
  22. providers: [
  23. provideModuleMap(LAZY_MODULE_MAP)
  24. ]
  25. }));
  26. app.set('view engine', 'html');
  27. app.set('views', DIST_FOLDER);
  28. // Example Express Rest API endpoints
  29. // app.get('/api/**', (req, res) => { });
  30. // Serve static files from /browser
  31. app.get('*.*', express.static(DIST_FOLDER, {
  32. maxAge: '1y'
  33. }));
  34. // All regular routes use the Universal engine
  35. app.get('*', (req, res) => {
  36. res.render('index', { req });
  37. });
  38. // Start up the Node server
  39. app.listen(PORT, () => {
  40. console.log(`Node Express server listening on http://localhost:${PORT}`);
  41. });

编译运行

  1. $ npm run build:ssr && npm run serve:ssr # 运行在 http://localhost:4000/