让vue-cli初始化后的项目集成支持SSR 2

该文章讲的还是关于vue查看源代码的问题,目的是用于渲染页面是vue页面能够看到源代码

上一篇文章使用的服务端渲染方法有点瑕疵,那就是项目打包以后并不能看到index.html,想要项目正常运行需要把整个项目文件夹放上去,而不是把dist里面的文件放上去就可以了。

所以这里跟大家介绍另一种方法,这种方法同样需要服务端来配合,

服务端配置可以参考如下链接

https://router.vuejs.org/zh-cn/essentials/history-mode.html

https://segmentfault.com/q/1010000006177894/a-1020000006619306

除此以外前端也需要配置一些东西

可以参考:https://www.npmjs.com/package/prerender-spa-plugin

其中的webpack.config.js其实就是webpack.base.config.js和 webpack.dev.config.js和 webpack.prod.config.js集合,我们主需要在 和 webpack.prod.config.js里面写入就可以了

//引入
const PrerenderSpaPlugin = require( 'prerender-spa-plugin')

//配置所需渲染的路由路径
new PrerenderSpaPlugin(
//将渲染的文件放到dist目录下
path. join( __dirname, '../dist'),
//需要预渲染的路由信息
[ '/', '/index', '/page1', '/page2', '/page3', '/page4', '/page5', '/page6'],
// [ '/'],
{
//在一定时间后再捕获页面信息,使得页面数据信息加载完成
captureAfterTime: 50000,
//忽略打包错误
ignoreJSErrors: true,
phantomOptions: '--web-security=false',
maxAttempts: 10,
}
),

然后config/index.js 中build 里面的assetsPublicPath最好改为绝对路径,避免出错

build: {
    //.......
assetsPublicPath: 'http://www.xxxxx.com/xxxxx/',
}

路由的 index.js 文件开启 history模式,并加上路径

export default new Router({
mode: 'history',
base: '/xxxxx/',//这里的路径注意和上面conig/index.js 中 build 的 assetsPublicPath保持一致
routes: [
{ path: '/index', name: 'index', component:index},
{ path: '/page1', name: 'page1', component:page1},
{ path: '/page2', name: 'page2', component:page2},
    //......
]
})


万事俱备准备打包,如果之前没有装过prerender 可能会提示找不到module ,

需要install一下npm install --save prerender-spa-plugin


打包上传测试


Note:如果碰到打开页面后刷新页面就崩掉变为空白的问题,那是后台配置设置的问题,具体操作百度一下



猜你喜欢

转载自blog.csdn.net/young_gao/article/details/80341723
今日推荐