VuePress 项目使用浏览器/DOM 中的 API 对象时报 XXX is not definded
触发条件:在项目 build 时, 项目内直接使用 window ,sessionStorage 等浏览器/DOM 中的 API 对象时报 XXX is not definded
主要原因:VuePress 是采用了 vue-ssr 服务端渲染, 项目在 build 时,则时通过 node.js 进行的服务端渲染,node.js 环境不包含此类对象,所以打包时就会抛出该问题
( 注:vue-ssr 采用了vue-router的Vue的SSR渲染,必须使用history作为路由模式 )
- 解决办法:如下
直接使用浏览器/DOM 中的 API原因的:可在 beforeMount、mounted 内调用解决
<script>
mounted () {
// 直接使用
console.log(window)
// 调用自定义方法引入
import('js方法路径').then(module => {
console.log(module)
})
},
</script>
组件原因:利用 vue 的动态组件
<template>
<component v-if="dynamicComponent" :is="dynamicComponent" />
</template>
<script>
data () {
return {
dynamicComponent: null
}
},
mounted () {
import('组件名').then(module => {
this.dynamicComponent = module.default
})
},
</script>
示例
- 如果是引入全局组件库,可在 enhanceApp.js 内引入, 方法如下
- 全局引入 Element 组件库
import Element from 'element-ui'
export default ({}) => {
Vue.use(Element)
}
- 全局按需引入 Element 组件库,js 方法引入同理
export default ({}) => {
import('element-ui').then(module => {
Vue.use(module.Button) // 引入Button组件
})
}
也可通过 mixin 混入
Vue.mixin({
mounted() {
import('element-ui').then(function (m) {
Vue.use(module.Button) // 引入Button组件
})
}
})
Powered by Waline v2.15.8