延迟加载 Angular 模块不会使用@nguniversal 渲染服务器端,而客户端路由和渲染工作

Lazy-loaded Angular modules don't get server side rendered with @nguniversal, while client side routing and rendering works

我们最近将我们的服务器端渲染 Angular 11 应用分解为延迟加载的模块,现在 SSR 不起作用。某些 URL 未正确路由并转到 404 包罗万象,而其他 URL 似乎已正确路由但显示白页(空 <router-outlet> 内容)。启用 Javascript 后,内容会在客户端正确呈现,或者如果我导航到任何 Angular 路由器链接。

我在较早的教程中读到,@nguniversal 曾经有一个用于延迟加载模块的模块映射,但 Angular 11 不需要它。

这是我的路线的样子:

const routes: Routes = [
  {
    path: '',
    redirectTo: 'start/',
    pathMatch: 'full'
  },
  {
    path: 'start',
    loadChildren: () => import('../home/home.module').then(m => m.HomeModule)
  },
  {
    path: 'blog',
    loadChildren: () => import('../blog/blog.module').then(m => m.BlogModule)
  },
  {
    path: 'ratgeber',
    loadChildren: () => import('../guide/guide.module').then(m => m.GuideModule)
  },
  {
    path: 'branchenbuch',
    loadChildren: () => import('../vendors/vendors.module').then(m => m.VendorsModule)
  },
  {
    path: 'galerien',
    loadChildren: () => import('../gallery/gallery.module').then(m => m.GalleryModule)
  },
  { path: '404/.', component: NotFoundComponent },
  { path: ':slug/.', component: StaticPageComponent },
  { path: '**', component: NotFoundComponent },

这是我在 server.ts

中的 Express 条目
export function app(): express.Express {
  const server = express()
  const distFolder = join(process.cwd(), 'dist/hp24-frontend/browser')
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index'

  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }))

  server.set('view engine', 'html')
  server.set('views', distFolder)

  // Example Express Rest API endpoints
  // server.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }))

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    const hostUrl = req.protocol + '://' + (req.get('X-Forwarded-Host') || req.get('Host'))
    res.render(indexHtml, {
      req,
      providers: [
        { provide: APP_BASE_HREF, useValue: req.baseUrl },
        { provide: HOST_URL, useValue: hostUrl },
      ]
    })
  })

  return server
}

这是我的angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "hp24-frontend": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "hp24",
      "architect": {
        "build": {
          "builder": "@angular-builders/custom-webpack:browser",
          "options": {
            "customWebpackConfig": {
              "path": "./webpack.config.js"
            },
            "outputPath": "dist/hp24-frontend/browser",
            "index": "src/index.html",
            "indexTransform": "index-html-transform.ts",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "aot": true,
            "assets": [
              "src/assets"
            ],
            "styles": [
              "src/styles/styles.scss"
            ],
            "scripts": [],
            "stylePreprocessorOptions": {
              "includePaths": [
                "src/styles"
              ]
            }
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "6kb",
                  "maximumError": "10kb"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-builders/custom-webpack:dev-server",
          "options": {
            "customWebpackConfig": {
              "path": "./webpack.config.js"
            },
            "browserTarget": "hp24-frontend:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "hp24-frontend:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "hp24-frontend:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles/variables/_colors.scss",
              "src/styles/styles.scss"
            ],
            "scripts": []
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "tsconfig.app.json",
              "tsconfig.spec.json",
              "e2e/tsconfig.json",
              "tsconfig.server.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "hp24-frontend:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "hp24-frontend:serve:production"
            }
          }
        },
        "server": {
          "builder": "@angular-builders/custom-webpack:server",
          "options": {
            "customWebpackConfig": {
              "path": "./webpack.config.js"
            },
            "outputPath": "dist/hp24-frontend/server",
            "main": "server.ts",
            "tsConfig": "tsconfig.server.json"
          },
          "configurations": {
            "production": {
              "outputHashing": "media",
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "sourceMap": false,
              "optimization": true
            }
          }
        },
        "serve-ssr": {
          "builder": "@nguniversal/builders:ssr-dev-server",
          "options": {
            "browserTarget": "hp24-frontend:build",
            "serverTarget": "hp24-frontend:server"
          },
          "configurations": {
            "production": {
              "browserTarget": "hp24-frontend:build:production",
              "serverTarget": "hp24-frontend:server:production"
            }
          }
        },
        "prerender": {
          "builder": "@nguniversal/builders:prerender",
          "options": {
            "browserTarget": "hp24-frontend:build:production",
            "serverTarget": "hp24-frontend:server:production",
            "routes": [
              "/"
            ]
          },
          "configurations": {
            "production": {}
          }
        }
      }
    }},
  "defaultProject": "hp24-frontend"
}

...这是我用于 postcss 和 tailwind 的 自定义 webpack 文件

const plugins = [
  require('postcss-import'),
  require('tailwindcss'),
  require('autoprefixer'),
]

module.exports = {
  module: {
    rules: [
      {
        test: /\.scss$/,
        loader: 'postcss-loader',
        options: {
          ident: 'postcss',
          syntax: 'postcss-scss',
          plugins: () => plugins
        }
      }
    ]
  }
};

这是我的主服务器模块:

import { NgModule } from '@angular/core'
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server'

import { AppModule } from './app.module'
import { AppComponent } from './app.component'
import { FlexLayoutServerModule } from '@angular/flex-layout/server'
import { SeoService } from './core/services/seo.service'

@NgModule({
  imports: [
    AppModule,
    ServerModule,
    ServerTransferStateModule,
    FlexLayoutServerModule
  ],
  providers: [SeoService],
  bootstrap: [AppComponent],
})
export class AppServerModule {}

关于我可能在这里遗漏的任何提示?

我发现了问题。 @nguniversal 正在删除我的尾部斜线,所以我不得不重写 server.ts 条目中的 Location.stripTrailingSlash 方法。

这是我的自定义 UrlSerializer,无需在路由器或组件中的各个路由器链接中对尾部斜杠进行硬编码。

import { UrlTree, DefaultUrlSerializer } from '@angular/router'
import { isPlatformBrowser } from '@angular/common'
import { InjectionToken } from '@angular/core'

export class TrailingSlashSerializer extends DefaultUrlSerializer {
  constructor(private platformId: InjectionToken<any>) {
    super()
  }
  serialize(tree: UrlTree): string {
    return this._withTrailingSlash(super.serialize(tree))
  }

  parse(url: string): UrlTree {
    if (isPlatformBrowser(this.platformId)) {
      return super.parse(this._withoutDot(url))
    } else {
      return super.parse(url)
    }
  }

  private _withoutDot(url: string): string {
    const splitOn = url.indexOf('?') > - 1 ? '?' : '#'
    const pathArr = url.split(splitOn)

    if (pathArr[0].endsWith('/.')) {
      pathArr[0] = pathArr[0].slice(0, -2)
    } else if (pathArr[0].endsWith('.')) {
      pathArr[0] = pathArr[0].slice(0, -1)
    }

    return pathArr.join(splitOn)
  }

  private _withDot(url: string): string {
    if (url.split('/').pop().indexOf('.') === -1) {
      if (url.endsWith('/')) {
        url += '.'
      } else if (!url.endsWith('/') && !url.endsWith('.')) {
        url += '/.'
      }
    }
    return url
  }

  private _withTrailingSlash(url: string): string {
    const splitOn = url.indexOf('?') > - 1 ? '?' : '#'
    const pathArr = url.split(splitOn)

    if (!pathArr[0].endsWith('/')) {
      const fileName: string = url.substring(url.lastIndexOf('/') + 1)
      if (fileName.indexOf('.') === -1 || fileName.indexOf('?') > -1) {
        pathArr[0] += '/'
      }
    } else {
      pathArr[0] += ''
    }
    return pathArr.join(splitOn)
  }
}

export const urlSerializerFactory = (platformId: InjectionToken<any>) => {
  return new TrailingSlashSerializer(platformId)
}

现在只需在您的应用模块的提供程序中使用序列化器工厂,如下所示:

import { UrlSerializer } from '@angular/router'
import { urlSerializerFactory } from './providers/trailing-slash.serializer'

@NgModule({
  providers: [
    {
      provide: UrlSerializer,
      useFactory: urlSerializerFactory,
      deps: [PLATFORM_ID]
    }
  ],
})