简体   繁体   English

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

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

We recently broke up our Server Side Rendered Angular 11 app into lazy-loaded modules and now SSR doesn't work.我们最近将我们的服务器端渲染 Angular 11 应用程序分解为延迟加载模块,现在 SSR 不起作用。 Some of the URLs don't get routed properly and go to the 404 catch-all while others seem to be routed properly but show a white page (empty <router-outlet> contents).一些 URL 没有正确路由,并且 go 到 404 包罗万象,而其他 URL 似乎路由正确但显示白页(空<router-outlet>内容)。 With Javascript enabled the content gets properly rendered on the client side or if I navigate to any of the Angular router links.启用 Javascript 后,内容会在客户端正确呈现,或者如果我导航到任何 Angular 路由器链接。

I read in older tutorials that there used to be a module map for lazy-loaded modules for @nguniversal but that should not be needed with Angular 11.我在较早的教程中读到,曾经有一个模块 map 用于 @nguniversal 的延迟加载模块,但 Angular 11 不需要它。

This is how my routes look like:这就是我的路线的样子:

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 },

And this is my Express entry in server.ts这是我在server.ts中的快速条目

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
}

This is my angular.json .这是我的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"
}

... and this is my custom webpack file that I use for postcss and tailwind. ...这是我用于 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
        }
      }
    ]
  }
};

And this is my main server module :这是我的主要服务器模块

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 {}

Any tips for what I might be missing here?关于我可能在这里遗漏的任何提示?

I found the problem.我发现了问题。 @nguniversal was stripping my trailing slashes so I had to override the Location.stripTrailingSlash method in my server.ts entry. @nguniversal正在剥离我的尾部斜杠,所以我不得不覆盖我的 server.ts 条目中的 Location.stripTrailingSlash 方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 7子路由延迟加载模块不起作用 - Angular 7 sub-routing lazy-loaded modules are not working Angular:使用路由对延迟加载的模块进行单元测试 - Angular: Unit testing lazy-loaded modules with routing 角度5:如何路由嵌套的延迟加载模块? - Angular 5: How to routing nested lazy-loaded modules? 安全地保护延迟加载的模块(Angular 2) - Securely Guarding Lazy-Loaded Modules (Angular 2) Angular 是呈现客户端还是服务器端? - Is Angular rendered client side or server side? Angular 5在加载应用程序时如何从服务器端渲染切换到客户端渲染 - Angular 5 how to switch from server side rendering to client side rendering when the app is loaded 在子延迟加载模块中使用参数进行角路由? 无法匹配每次抛出的任何路线 - Angular routing with parameters in a child, lazy-loaded module? Can't match any routes thrown every time 具有多个命名出口的延迟加载模块上的Angular2路由 - Angular2 Routing on lazy-loaded module with multiple named outlets 角度的 <custom-component> 在延迟加载的模块上不起作用 - Angular <custom-component> doesnt work on lazy-loaded modules 将 Angular 从 8 更新到 9 后延迟加载的模块警告 - Lazy-loaded modules warnings after updating Angular from 8 to 9
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM