首页 > 解决方案 > 服务器端渲染中只能在浏览器中运行的包错误

问题描述

我在我的 SSR Nuxt 项目中使用localForage 。

在我的Nuxt-Page-Component

...
<script>
import localforage from 'localforage';
export default{
    mounted(){
        localforage.getItem('something', value => {
            ...
        });
    }
}
</script>
...

因为localforage只能在浏览器中工作,所以每次我尝试以服务器端渲染模式访问页面时都会出现如下错误(尽管页面可以被渲染并且页面可以按我想要的方式工作)

错误未找到可用的存储方法。在 node_modules/localforage/dist/localforage.js:2743:25

在此处输入图像描述

我尝试在我的项目中使用localforage作为自定义插件,我将其配置为仅限客户端的插件

// nuxt.config.js
module.exports = {
    ...    
    plugins:[
        { src: '~/plugins/localforage', ssr: false }
    ],
    ...
}

// localforage.js
import localforage from 'localforage';
window.localforage = localforage;

// localforage.js (or as a Vue plugin)
import localforage from 'localforage';
import Vue from 'vue';
Vue.use({
    install(Vue){
        Vue.prototype.$localforage = localforage;
    }
});

但是我只能得到更多的错误,而且这一次页面无法渲染。

我该如何解决这个错误,我已经用谷歌搜索过了,但它没有任何帮助。

非常感谢!

(不是以英语为母语的人,如有错误请见谅)

标签: javascriptvue.jsnuxt.jsserver-side-rendering

解决方案


挂载中的延迟加载模块怎么样?

<script>
export default{
    async mounted(){
        const localforage = await import('localforage')
        localforage.getItem('something', value => {
            ...
        });
    }
}
</script>

推荐阅读