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

发布时间:2021-03-07 22:10

我们最近将我们的服务器端渲染 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 {}

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

回答1

我发现了问题。 @nguniversal 正在去除我的尾部斜杠,所以我不得不在我的 server.ts 条目中覆盖 Location.stripTrailingSlash 方法。