Angular Universal: Error: No NgModule metadata found for '[object Object]'

Angular Universal: Error: No NgModule metadata found for '[object Object]'

我正在开发一个 github 存储库,它是一个 angular 示例应用程序,您可以查看它 here。 现在我正在尝试添加 Angular Universal 并将其部署到 firebase(这就是 functions 文件夹的原因)。一切正常,漏洞构建过程和部署,但是当 运行 在本地主机中使用 SSR 时,我遇到了这个错误:

Error: No NgModule metadata found for '[object Object]'.
at NgModuleResolver.resolve (/Users/iramos/WebstormProjects/angular7-example-app/functions/dist/server.js:60692:23)
at CompileMetadataResolver.getNgModuleMetadata (/Users/iramos/WebstormProjects/angular7-example-app/functions/dist/server.js:59334:43)
at JitCompiler._loadModules (/Users/iramos/WebstormProjects/angular7-example-app/functions/dist/server.js:66754:51)
at JitCompiler._compileModuleAndComponents (/Users/iramos/WebstormProjects/angular7-example-app/functions/dist/server.js:66735:36)
at JitCompiler.compileModuleAsync (/Users/iramos/WebstormProjects/angular7-example-app/functions/dist/server.js:66695:37)
at CompilerImpl.compileModuleAsync (/Users/iramos/WebstormProjects/angular7-example-app/functions/dist/server.js:87477:31)
...

重现错误的步骤:

  1. 克隆存储库
  2. npm i;
  3. npm 运行 build:ssr 然后 npm 运行 start:ssr
  4. 转到localhost:4000

我将把最重要的部分粘贴到这里,但你可以查看 hole repo。

package.json

"scripts": {
    "start:ssr": "node functions/dist/server",
    "build": "ng build",
    "build:prod": "ng build --prod",
    "build:prod:es": "ng build --configuration=production-es",
    "build:server:prod": "ng run angularexampleapp:server:production",
    "build:client-and-server-bundles": "npm run build:prod && npm run build:prod:es && npm run build:server:prod",
    "compile:server": "webpack --config webpack.server.config.js --progress --colors",
    "build:ssr": "npm run build:client-and-server-bundles && npm run compile:server"
}

webpack.server.config.js

// Work around for https://github.com/angular/angular-cli/issues/7200

const path = require('path');
const webpack = require('webpack');

module.exports = {
  mode: 'none',
  entry: {
    // This is our Express server for Dynamic universal
    server: './server.ts'
  },
  target: 'node',
  resolve: {extensions: ['.ts', '.js']},
  optimization: {
    minimize: false
  },
  output: {
    // Puts the output at the root of the dist folder
    path: path.join(__dirname, 'functions/dist'),
    filename: '[name].js'
  },
  module: {
    rules: [
      {test: /\.ts$/, loader: 'ts-loader'}
    ]
  },
  plugins: [
    new webpack.ContextReplacementPlugin(
      // fixes WARNING Critical dependency: the request of a dependency is an expression
      /(.+)?angular(\|\/)core(.+)?/,
      path.join(__dirname, 'src'), // location of your src
      {} // a map of your routes
    ),
    new webpack.ContextReplacementPlugin(
      // fixes WARNING Critical dependency: the request of a dependency is an expression
      /(.+)?express(\|\/)(.+)?/,
      path.join(__dirname, 'src'),
      {}
    )
  ]
};

server.ts

import 'reflect-metadata';
import 'zone.js/dist/zone-node';

import {enableProdMode} from '@angular/core';
// Express Engine
import {ngExpressEngine} from '@nguniversal/express-engine';
// Import module map for lazy loading
import {provideModuleMap} from '@nguniversal/module-map-ngfactory-loader';

import * as express from 'express';
import {join} from 'path';

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express server
const app = express();

const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'functions/dist/browser');

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./functions/dist/server/main');

// Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
  bootstrap: AppServerModuleNgFactory,
  providers: [
    provideModuleMap(LAZY_MODULE_MAP)
  ]
}));

app.set('view engine', 'html');
app.set('views', DIST_FOLDER);

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

// All regular routes use the Universal engine
app.get('*', (req, res) => {
  res.render('index', {req});
});

// Start up the Node server
app.listen(PORT, () => {
  console.log(`Node Express server listening on http://localhost:${PORT}`);
});

angular.json

...
"configurations": {
    "production-en": {
        "optimization": true,
        "outputHashing": "all",
        "sourceMap": false,
        "extractCss": true,
        "namedChunks": false,
        "aot": true,
        "extractLicenses": true,
        "vendorChunk": false,
        "buildOptimizer": true,
        "serviceWorker": true,
        "baseHref": "/",
        "budgets": [
           {
             "type": "initial",
             "maximumWarning": "2mb",
             "maximumError": "5mb"
           }
        ],
        "fileReplacements": [
           {
             "replace": "src/environments/environment.ts",
             "with": "src/environments/environment.prod.ts"
           }
        ]
    }
}

...

"server": {
    "builder": "@angular-devkit/build-angular:server",
    "options": {
       "outputPath": "functions/dist/server",
       "main": "src/main.server.ts",
       "tsConfig": "src/tsconfig.server.json"
    },
    "configurations": {
       "production": {
          "fileReplacements": [
            {
              "replace": "src/environments/environment.ts",
              "with": "src/environments/environment.prod.ts"
            }
          ],
          "stylePreprocessorOptions": {
            "includePaths": [
              "src/app/styles"
            ]
          }
        }
      }
    }
 }

我已经尝试过的事情:

  1. 从 angular.json
  2. 中删除 "outputHashing"
  3. 去除延迟加载路由(英雄模块中只有一个)
  4. 关闭 angular json 配置中的优化标志

None 有效。

如有任何帮助,我将不胜感激!请!!

谢谢!

最后,我不得不删除一个包含构建过程中包含的一些脚本的文件夹。您可以在 github 存储库中找到最终代码。