我按照教程here实现了服务器端渲染Angular 4应用程序。但是,我不知道如何解决与&#34相关的问题;文档未定义"在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)
我搜索了很多与&#34相关的帖子;文档没有定义&#34;,大多数只是解释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}!`);
});
提前致谢。
答案 0 :(得分:0)
NodeJs不支持window, document, navigator
类型。因此,解决方案是将文件夹复制到另一个目录中,例如在src/server-mocks/
中,并将所有document
类型替换为global
文件中的index.js
并配置{{1}通过添加以下代码..
webpack.server.config.js