【问题标题】:Angular 4 Server-side rendering with Node.js (ReferenceError: document is not defined)Angular 4 使用 Node.js 进行服务器端渲染(ReferenceError:文档未定义)
【发布时间】:2017-10-19 17:26:03
【问题描述】:

我按照教程 here 实现了一个服务器端渲染 Angular 4 应用程序。但是,我不知道如何解决与 Node.js 中“文档未定义”相关的问题。我知道 Node.js 没有 DOM,因为它不是“浏览器”。但是,我非常需要在服务器中渲染应用程序以进行 SEO,但我不知道如何解决这些问题。我无法更改代码,因为它是第三方代码,嗯……有什么建议吗?

/var/www/nodejs/example.com/node_modules/custom-event/index.js:24
'function' === typeof document.createEvent ? function CustomEvent (type, params) {
                  ^
ReferenceError: document is not defined at Object.<anonymous> (/var/www/nodejs/example.com/node_modules/custom-event/index.js:24:23)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/var/www/nodejs/example.com/node_modules/crossvent/src/crossvent.js:3:19)
    at Module._compile (module.js:569:30)

我搜索了很多关于“文档未定义”的帖子,其中大多数只是解释说node.js没有DOM,但没有提供任何解决方案。

如果你需要我的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 PORT = 4000;

enableProdMode();

const app = express();

let 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}!`);
});

提前致谢。

【问题讨论】:

  • 这有什么更新吗?
  • 我“暂时”放弃了......同时仍在等待更好的答案。一些教程建议删除那些需要“文档”、“窗口”等的第三方脚本,并专门为服务器构建它,同时为客户端提供完整的应用程序。但是,我没有尝试这个,因为临时服务器渲染功能不是我的项目优先级......祝你好运!

标签: node.js angular


【解决方案1】:

NodeJs 不支持window, document, navigator 类型。因此,解决方案是将文件夹复制到另一个目录中,例如在src/server-mocks/ 中,并在index.js 文件中将所有document 类型替换为global,并通过添加以下代码来配置webpack.server.config.js..

const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');

 new NormalModuleReplacementPlugin(
      /crossvent(\\|\/)src(\\|\/)crossvent.js/,
      path.join(__dirname, 'src/server-mocks/crossvent/src/crossvent.js')    
    ),

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-05-06
  • 2021-02-22
  • 2018-03-21
  • 2016-07-16
  • 2017-09-06
  • 1970-01-01
  • 2017-06-20
  • 2023-04-01
相关资源
最近更新 更多