vuepress打包报错localStorage is not defined

2023年9月7日
大约 1 分钟

vuepress打包报错localStorage is not defined

错误日志

- Rendering pages /spring/spring-annotate.htmlReferenceError: window is not defined
  at Proxy.initialize (F:\yoodb\yoodb\.vuepress\.temp\.server\app.js:42613:7)
  at Proxy.created (F:\yoodb\yoodb\.vuepress\.temp\.server\app.js:42608:10)
  at callWithErrorHandling (F:\yoodb\node_modules\@vue\runtime-core\dist\runtime-core.cjs.prod.js:119:36)
  at callWithAsyncErrorHandling (F:\yoodb\node_modules\@vue\runtime-core\dist\runtime-core.cjs.prod.js:128:21)
  at callHook (F:\yoodb\node_modules\@vue\runtime-core\dist\runtime-core.cjs.prod.js:2801:5)
  at applyOptions (F:\yoodb\node_modules\@vue\runtime-core\dist\runtime-core.cjs.prod.js:2713:9)
  at finishComponentSetup (F:\yoodb\node_modules\@vue\runtime-core\dist\runtime-core.cjs.prod.js:5883:9)
  at handleSetupResult (F:\yoodb\node_modules\@vue\runtime-core\dist\runtime-core.cjs.prod.js:5834:5)
  at setupStatefulComponent (F:\yoodb\node_modules\@vue\runtime-core\dist\runtime-core.cjs.prod.js:5811:13)
  at setupComponent (F:\yoodb\node_modules\@vue\runtime-core\dist\runtime-core.cjs.prod.js:5770:11)
  \ Rendering pages /spring/spring-aop.htmlF:\yoodb\yoodb\.vuepress\.temp\.server\app.js:42552
  typeId = localStorage.getItem("host");
  ^

ReferenceError: localStorage is not defined
at Proxy.grabDataDetail (F:\yoodb\yoodb\.vuepress\.temp\.server\app.js:42552:9)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)

原因分析

在vuepress中执行npm run docs:build命令进行打包时报错,这是由于localStorage是浏览器中使用的全局对象,但是在构建静态页面时无法访问到该对象,从而导致打包报错。

解决方法

在js代码中判断当前环境是否是浏览器访问行为,之后根据判断情况再访问localStorage对象,这种方式就避免了在打包时报错,具体代码参考如下:

if (typeof window !== "undefined") {
    localStorage.setItem("host", "www.yoodb.com");
}

上述代码逻辑:当前环境为浏览器访问行为时,需执行localStorage相关操作,反之不执行。这样就可以避免在构建静态页面时访问localStorage对象,从而解决打包报错问题。