nodejs vuepress 使用 npm run build 时报错:

⠋ Rendering 10 pagesReferenceError: document is not defined
    at file:///D:/git/huyunan/interview/docs/.vuepress/.temp/.server/assets/index.html-D64q-nPL.js:36:7

  if (document) {
    const link = typeof document && document.createElement('link');
    link.rel = 'preload';
    link.href = `/interview/swiper/${jpg}`;
    link.as = 'image';
    return link
  }
  return {}

加了 if 判断也 build 不过去。

解决方法:使用 typeof 可以安全地检查一个变量是否存在以及它的类型,typeof 不报错

if (typeof document !== 'undefined') {

也可以用下面这种写法

typeof document !== 'undefined' && document.head.appendChild(links[0]);

再次 npm run build 不报错了。

更多推荐