renderModule 不是函数:angular12 @nguniversal 仅用于预渲染

renderModule is not a function : angular12 @nguniversal on prerender only

目前正在将 static angular 8 网站 迁移到 angular 12prerendering 页面在本地失败。

第一步是使用 ng add @nguniversal/express-engine 生成最新的脚手架,然后清理以前的 angular8/universal 代码。

✅ 我可以成功 运行 dev:ssr, build:ssr, serve:ssr.

"dev:ssr": "ng run website:serve-ssr",
"build:ssr": "ng build && ng run website:server",
"serve:ssr": "node dist/server/main.js",

❌当运行宁npm run prerender出现如下错误

> ng run website_en:prerender

✔ Browser application bundle generation complete.
✔ Copying assets complete.
✔ Index html generation complete.
Build at: 2021-08-02T13:56:58.216Z - Hash: b2a4bcc276d1ce7a8de9 - Time: 26662ms

✔ Server application bundle generation complete.
Build at: 2021-08-02T13:57:00.109Z - Hash: 0f46572a7951c62abea9 - Time: 31768ms

✖ Prerendering routes to ~/website/dist/en failed.
renderModule is not a function

我怀疑与之前 angular8 中的代码有一些冲突,但在线查看大多数代码示例与我的项目相似。项目也非常简约,没有太多的依赖性冲突或挣扎。

完整日志

$ npm run prerender

> website@0.0.0 prerender ~/website
> ng run website_en:prerender

Warning: Support was requested for IE 11 in the project's browserslist configuration. IE 11 support is deprecated since Angular v12.
For more information, see https://angular.io/guide/browser-support
✔ Browser application bundle generation complete.
✔ Copying assets complete.
✔ Index html generation complete.

Initial Chunk Files                   | Names         |      Size
main.2703b1ee464983914c90.js          | main          | 549.78 kB
polyfills-es5.2669892dbe0306fd6806.js | polyfills-es5 | 196.24 kB
polyfills.09b63a2959800df8a004.js     | polyfills     | 103.74 kB
styles.ee78a15edec5586952fa.css       | styles        |  51.58 kB
runtime.0ad0b9f7bc4456da9d9e.js       | runtime       |   3.41 kB

                                      | Initial Total | 904.75 kB

Lazy Chunk Files                      | Names         |      Size
459.ca33d2d2dfd51ae7e99b.js           | -             |  12.67 kB
341.48060e5c202342d1cc32.js           | -             |  12.41 kB
34.4553ce01726f9dd74f9c.js            | -             |   9.67 kB
846.d0bde86d8ef5c235cb29.js           | -             |   6.73 kB
284.f7119b6b03003373bf17.js           | -             |   5.25 kB
common.a1228fa90f251ccea342.js        | common        | 922 bytes

Build at: 2021-08-02T13:56:58.216Z - Hash: b2a4bcc276d1ce7a8de9 - Time: 26662ms
✔ Server application bundle generation complete.

Initial Chunk Files | Names         |    Size
main.js             | main          | 4.50 MB

                    | Initial Total | 4.50 MB

Build at: 2021-08-02T13:57:00.109Z - Hash: 0f46572a7951c62abea9 - Time: 31768ms
✖ Prerendering routes to ~/website/dist/en failed.
renderModule is not a function

angular.json

我相信我的 angular.json 配置正确

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "website_en": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/en",
            "index": "src/index.html",
            "main": "src/main.ts",
            "tsConfig": "src/tsconfig.app.json",
            "polyfills": "src/polyfills.ts",
            "assets": [
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "development": {},
            "production": {
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "optimization": {
                "scripts": true,
                "styles": {
                  "minify": true,
                  "inlineCritical": false
                },
                "fonts": true
              },
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ]
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "website_en:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "website_en:build:production"
            },
            "development": {
              "browserTarget": "website_en:build:development"
            }

          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "website_en:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "karmaConfig": "./karma.conf.js",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "scripts": [],
            "styles": [
              "src/styles.scss"
            ],
            "assets": [
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        },
        "server": {
          "builder": "@angular-devkit/build-angular:server",
          "options": {
            "outputPath": "dist/server",
            "main": "server.ts",
            "tsConfig": "src/tsconfig.server.json"
          },
          "configurations": {
            "production": {},
            "development": {}
          }
        },
        "serve-ssr": {
          "builder": "@nguniversal/builders:ssr-dev-server",
          "configurations": {
            "development": {
              "browserTarget": "website_en:build:development",
              "serverTarget": "website_en:server:development"
            },
            "production": {
              "browserTarget": "website_en:build:production",
              "serverTarget": "website_en:server:production"
            }
          },
          "defaultConfiguration": "development"
        },
        "prerender": {
          "builder": "@nguniversal/builders:prerender",
          "options": {
            "browserTarget": "website_en:build:production",
            "serverTarget": "website_en:server:production",
            "routesFile": "./static.paths.txt"
          },
          "configurations": {
            "production": {}
          },
          "defaultConfiguration": "production"
        }
      }
    }
  },
  "defaultProject": "website_en",
  "cli": {
    "warnings": {
      "typescriptMismatch": false
    }
  },
  "schematics": {
    "@schematics/angular:component": {
      "prefix": "app",
      "styleext": "css"
    },
    "@schematics/angular:directive": {
      "prefix": "app"
    }
  }
}

static.paths.txt

我的文件 static.paths.txt 接缝被正确加载为 npm 简要报告在触发错误之前生成 4 个 url

/contact
/resources
/legal

tsconfig.json

我猜 tsconfig.json

没什么可期待的
{
  "compileOnSave": false,
  "compilerOptions": {
    "importHelpers": true,
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "module": "esnext",
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ],
    "baseUrl": "./"
  },
  "include": [
    "server.ts"
  ]
}

tsconfig.app.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "types": []
  },
  "include": [
    "**/*.ts"
  ],
  "exclude": [
    "test.ts",
    "**/*.spec.ts",
    "main.server.ts",
    "app/app.server.ts"
  ]
}

tsconfig.server.json

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    // Set the module format to "commonjs":
    "module": "commonjs",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ],
  // Add "angularCompilerOptions" with the AppServerModule you wrote
  // set as the "entryModule".
  "angularCompilerOptions": {
    "entryModule": "app/app.server#AppServerModule"
  }
}

server.ts

我遇到的唯一问题是关于导入快递时生成的 server.ts。我的 tsconfig 有问题,我可以轻松修复,但使用 import express from "express";。再次,动态 ssr 按预期工作。

Error: server.ts:13:18 - error TS2349: This expression is not callable.
  Type 'typeof e' has no call signatures.

13   const server = express();
                    ~~~~~~~

  server.ts:4:1
    4 import * as express from "express";
      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Type originates at this import. A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Consider using a default import or import require here instead.

版本

"dependencies": {
    "@angular/animations": "^12.1.4",
    "@angular/common": "^12.1.4",
    "@angular/compiler": "^12.1.4",
    "@angular/core": "^12.1.4",
    "@angular/forms": "^12.1.4",
    "@angular/http": "^7.2.16",
    "@angular/platform-browser": "^12.1.4",
    "@angular/platform-browser-dynamic": "^12.1.4",
    "@angular/platform-server": "^12.1.4",
    "@angular/router": "^12.1.4",
    "@nguniversal/express-engine": "^12.1.0",
    "@ngx-translate/core": "^13.0.0",
    "@ngx-translate/http-loader": "^6.0.0",
    "@sentry/browser": "^6.10.0",
    "aos": "^2.3.4",
    "core-js": "^3.16.0",
    "country-flag-emoji": "^1.0.3",
    "express": "^4.15.2",
    "express-sslify": "^1.2.0",
    "geo-tz": "^6.0.1",
    "mapbox-gl": "^2.4.0",
    "rxjs": "^7.3.0",
    "tslib": "^2.3.0",
    "web-animations-js": "^2.3.2",
    "zone.js": "^0.11.4"
  }

为了解决这个问题,我先睡了一觉,然后使用 angular-ci 生成了一个全新的 angular 项目,然后添加 @nguniversal/express-engine 以查看是否有任何重大差异。

npm install -g @angular/cli
ng add @nguniversal/express-engine
npm run prerender

发现我的 main.server.ts 文件没有正确初始化。现在按预期工作。

✅ 正确 main.server.ts 版本

/***************************************************************************************************
 * Initialize the server environment - for example, adding DOM built-in types to the global scope.
 *
 * NOTE:
 * This import must come before any imports (direct or transitive) that rely on DOM built-ins being
 * available, such as `@angular/elements`.
 */
import '@angular/platform-server/init';

import { enableProdMode } from '@angular/core';

import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

export { AppServerModule } from './app/app.server';
export { renderModule, renderModuleFactory } from '@angular/platform-server';

main.server.ts

的上一版本
import { environment } from './environments/environment';
import { enableProdMode } from '@angular/core';

enableProdMode();

export {AppServerModule} from './app/app.server';