前言
由于官网有SEO需要,因此对现官网项目进行ssr的整改兼容,在调试的过程中遇到了不少问题。本来在官网的demo项目中使用是比较顺畅的,但是由于本项目比较大复杂性比较高,踩了不少的坑。以下是我在调试过程中遇到的一些问题汇总,希望其他人可以避开这些坑。
1. 使用浏览器 API报错问题
在运行服务的时候,通常会遇到一下的一些报错
ReferenceError: window is not defined
或者
ReferenceError: document is not defined
由于 Universal 应用并没有运行在浏览器中,因此该服务器上可能会缺少浏览器的某些 API 和其它能力。比如,服务端应用不能引用浏览器独有的全局对象,比如 window、document、navigator 或 location。如果直接使用会导致运行的时候出现报错。因此,我们需要对使用浏览器的API方法做好兼容。
方案1:在server.ts,引入domino做兼容
const domino = require('domino');
const win = domino.createWindow(template);
global['window'] = win;
global['document'] = win.document;
global['CSS'] = null;
global['Prism'] = null;
global