如何在Angular Unviersal Project中的服务器上预渲染?

时间:2019-02-11 03:23:42

标签: angular serverside-rendering angular-universal

我正在使用Angular Universal的TransferState模块在服务器端调用api。大约需要6到7秒钟,即可实现服务器端渲染。 因此,当重新加载页面时,每次都能在6到7秒后看到加载的页面。加载页面时,仅在服务器上调用这些api。 如何在服务器上预渲染此页面,以缩短加载时间?

2 个答案:

答案 0 :(得分:0)

您可以运行基于预渲染的Angular Universal:

package.json

 "build:prerender": "npm run build:universal && npm run generate:prerender",
 "generate:prerender": "node prerender.js"

prerender.ts

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

const domino = require('domino');
const fs = require('fs');
const path = require('path');
const template = fs.readFileSync(path.join(__dirname, '.', 'dist', 'index.html')).toString();
const win = domino.createWindow(template);
const files = fs.readdirSync(`${process.cwd()}/dist-server`);

global['window'] = win;
Object.defineProperty(win.document.body.style, 'transform', {
  value: () => {
    return {
      enumerable: true,
      configurable: true,
    };
  },
});
global['document'] = win.document;
global['CSS'] = null;
// global['XMLHttpRequest'] = require('xmlhttprequest').XMLHttpRequest;
global['Prism'] = null;

// Load zone.js for the server.
import 'zone.js/dist/zone-node';
import 'reflect-metadata';
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';
import { join } from 'path';

import { enableProdMode } from '@angular/core';
// Faster server renders w/ Prod mode (dev mode never needed)
enableProdMode();

// Express Engine
import { ngExpressEngine } from '@nguniversal/express-engine';
// Import module map for lazy loading
import { provideModuleMap } from '@nguniversal/module-map-ngfactory-loader';
import { renderModuleFactory } from '@angular/platform-server';
import { ROUTES } from './static.paths';

// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const mainFiles = files.filter((file) => file.startsWith('main'));
const hash = mainFiles[0].split('.')[1];
const { AppServerModuleNgFactory, LAZY_MODULE_MAP } = require(`./dist-server/main.${hash}`);
import { REQUEST, RESPONSE } from '@nguniversal/express-engine/tokens';

const BROWSER_FOLDER = join(process.cwd(), 'static');

// Load the index.html file containing referances to your application bundle.
const index = readFileSync(join('dist', 'index.html'), 'utf8');

let previousRender = Promise.resolve();

// Iterate each route path
ROUTES.forEach((route) => {
  const fullPath = join(BROWSER_FOLDER, route);

  // Make sure the directory structure is there
  if (!existsSync(fullPath)) {
    let syncpath = BROWSER_FOLDER;
    route.split('/').forEach((element) => {
      syncpath = syncpath + '/' + element;
      mkdirSync(syncpath);
    });
  }

  // Writes rendered HTML to index.html, replacing the file if it already exists.
  previousRender = previousRender
    .then((_) =>
      renderModuleFactory(AppServerModuleNgFactory, {
        document: index,
        url: route,
        extraProviders: [
          provideModuleMap(LAZY_MODULE_MAP),
          {
            provide: REQUEST,
            useValue: { cookie: '', headers: {} },
          },
          {
            provide: RESPONSE,
            useValue: {},
          },
          {
            provide: 'ORIGIN_URL',
            useValue: environment.host,
          },
        ],
      }),
    )
    .then((html) => writeFileSync(join(fullPath, 'index.html'), html));
});

static.paths.ts

export const ROUTES = ['/routePrerenderPage', '/home' ];

答案 1 :(得分:0)

基本上,要渲染Angular,您需要准备以下这些东西:

  1. 页面路线 如果您有两个页面,例如“家”和“联系”,那么您的最终项目结构应如下所示:

| ---根 | --- index.html | --- /首页     | --- index.html | --- /联系     | --- index.html

  1. 渲染引擎 您需要使用渲染引擎通过在渲染引擎中循环路由参数来获取index.html文件。在Angular中,我们使用renderModuleFactory()作为渲染引擎。

您可以参考这篇文章以了解更多详细信息:Prerender Angular and Host It on AWS S3.