与Nunjucks相比,Angular Universal慢速渲染

时间:2019-01-31 07:58:10

标签: angular angular-universal

我已经在Angular 6应用中添加了Angular Universal,与库存的Angular相比,这是一个很大的收益,但是对于70个项目的页面,渲染时间约为250毫秒,而在我使用Nunjucks构建的类似前端中,它约为40毫秒(1个API调用大约是35个)。

渲染缓慢的原因是什么?将来可以改善吗?我看到的主要问题是Angular应用程序是在每个请求上创建的,但这不是唯一的事情,因为长页和短页之间存在很大差异。

我正在使用nginx + passenger

为应用程序提供服务

这是我的服务器。

// These are important and needed before anything else
import 'zone.js/dist/zone-node';
import 'reflect-metadata';

import { renderModuleFactory } from '@angular/platform-server';
import { enableProdMode } from '@angular/core';

import * as cookieParser from 'cookie-parser';
import * as express from 'express';
import { join } from 'path';
import { readFileSync } from 'fs';

// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();
const compression = require('compression');
// Express server
const app = express();
app.use(compression());
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(process.cwd(), 'dist');

// Our index.html we'll use as our template
const template = readFileSync(join(DIST_FOLDER, 'browser', 'index.html')).toString();

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

const { provideModuleMap } = require('@nguniversal/module-map-ngfactory-loader');

app.use(cookieParser('XXXXX'));

app.engine('html', (_, options, callback) => {
  renderModuleFactory(AppServerModuleNgFactory, {
    // Our index.html
    document: template,
    url: options.req.url,
    // DI so that we can get lazy-loading to work differently (since we need it to just instantly render it)
    extraProviders: [
      provideModuleMap(LAZY_MODULE_MAP),
      {
        provide: 'REQUEST',
        useValue: options.req
      },
      {
        provide: 'RESPONSE',
        useValue: options.req.res
      }
    ]
  }).then(html => {
    callback(null, html);
  });
});

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

// Server static files from /browser
app.get('*.*', express.static(join(DIST_FOLDER, 'browser')));

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

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

任何见解都会受到赞赏。

0 个答案:

没有答案