vuepress打包报错 localStorage is not defined

简介: vuepress打包报错 localStorage is not defined

vuepress打包报错 localStorage is not defined

原因

在 VuePress 中,localStorage 是在浏览器中使用的全局对象。所以,在构建静态页面时,无法访问到该对象,从而会导致打包报错。

解决方法

通过在代码中判断当前环境是否为浏览器,然后再访问 localStorage 对象。可以使用以下代码来避免打包报错:

if (typeof window !== "undefined") {
   
  // 在浏览器环境下执行 localStorage 相关操作
  localStorage.setItem("key", "value");
}

这段代码的意思是:如果当前环境为浏览器,则执行 localStorage 相关操作;否则不执行。这样就可以避免在构建静态页面时访问 localStorage 对象,从而解决打包报错问题。

目录
相关文章
|
9月前
|
JavaScript
VUE上传功能本地上传正常,打包上传后报错TypeError: ***.upload.addEventListener is not a function
VUE上传功能本地上传正常,打包上传后报错TypeError: ***.upload.addEventListener is not a function
327 0
|
8天前
|
小程序
微信小程序启动报错 WXML file not found: ./miniprogram_npm/@vant/weapp/action-sheet/index.wxml
微信小程序启动报错 WXML file not found: ./miniprogram_npm/@vant/weapp/action-sheet/index.wxml
46 3
|
8天前
|
小程序 开发工具 开发者
【微信小程序】微信开发者工具 引用 vant-weapp时“miniprogram/node_modules/@babel/runtime/index.js: 未找到npm包入口文件” 解决办法
【微信小程序】微信开发者工具 引用 vant-weapp时“miniprogram/node_modules/@babel/runtime/index.js: 未找到npm包入口文件” 解决办法
42 1
|
8天前
|
Web App开发 JavaScript
Vue download file
Vue download file
|
8天前
报错You may use special comments to disable some warnings.vue-cli脚手架关闭eslint的步骤
报错You may use special comments to disable some warnings.vue-cli脚手架关闭eslint的步骤
|
6月前
|
Web App开发 JavaScript
vue踩坑-Error: Can't resolve 'sass-loader' in 'E:\Element-UI-master\src\components'
vue踩坑-Error: Can't resolve 'sass-loader' in 'E:\Element-UI-master\src\components'
50 0
|
9月前
|
JavaScript 前端开发 API
vite.config.js 无法使用__dirname的解决方法
在使用 vite 的时候发现,在其 vite.config 文件中无法使用 __dirname 来代表当前目录,所有经过一番了解之后有了这篇文章。
288 0
|
JavaScript
vue.js项目打包报错Error: You appear to be using a native ECMAScript module configuration file
vue.js项目打包报错Error: You appear to be using a native ECMAScript module configuration file
191 0
vite2 打包的时候vendor-xxx.js文件过大的解决方法
vite2是一个非常好用的工具,只是随着代码的增多,打包的时候 vendor-xxxxxx.js 文件也越来越大,这就郁闷了。
310 0
|
JavaScript
vue使用js-file-download完成导出功能
1.安装js-file-download 2.引入对应的功能模块 3.代码段
165 0