从Angular 4.4.0迁移到Angular 5.2.0会导致服务器端呈现错误

我正在将我的角度应用程序从4.4.0迁移到5.2.0,它支持服务器端渲染.

在angular(v5)npm start中运行命令时,我收到此错误

src/server.ts(5,42): error TS2307: Cannot find module '../dist/ngfactory/src/app/app.server.module.ngfactory'.

另外,我检查不包含相同文件的dist文件夹.
我认为在配置上需要改变一些东西来修复它,我错过了.
有没有人面临同样的问题?

server.ts包含:

import 'reflect-metadata';
import 'zone.js/dist/zone-node';
import { platformServer, renderModuleFactory } from '@angular/platform-server'
import { enableProdMode } from '@angular/core'
import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory'
import * as express from 'express';
import { readFileSync } from 'fs';
import { join } from 'path';

const compression = require('compression')

const PORT = 4000;
let forceHttps = false;
const livehoststring = '-';
const livehost = '-';
const staticlivehost = '-';

enableProdMode();

const app = express();

app.use(compression());

const template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

app.engine('html', (_, options, callback) => {
  const opts = { document: template, url: options.req.url };

  renderModuleFactory(AppServerModuleNgFactory, opts)
    .then(html => callback(null, html));
});

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

app.get('*.*', express.static(join(__dirname, '..', 'dist')));

app.get('*', (req, res) => {
  res.render('index', { req });
});

app.listen(PORT, () => {
  console.log(`listening on http://localhost:${PORT}!`);
});

看完一些文章后,似乎我必须从不同的位置导入AppServerModuleNgFactory.但我无法找到确切的位置.

最佳答案 我通过替换server.ts中的AppServerModuleNgFactory导入路径解决了这个问题,如下所示:

const {  AppServerModuleNgFactory } = (module as any).exports;
// import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory'

通过将此替换为上面的npm start命令将正常工作.

(PS:但之后我跑了新错误)

Cannot read property ‘moduleType’ of undefined

Solution for this problem here

点赞