初始化创建一个项目vue create test添加预渲染依赖npm prerender-spa-plugin -D代码vue.config.jsconst PrerenderSPAPlugin = require(prerender-spa-plugin);const Renderer = PrerenderSPAPlugin.Puppetee...
初始化
创建一个项目
vue create test
添加预渲染依赖
npm prerender-spa-plugin -D
代码
vue.config.js
const PrerenderSPAPlugin = require("prerender-spa-plugin");
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer;
const path = require("path");
module.exports = {
configureWebpack: (config) => {
if (process.env.NODE_ENV !== "production") return;
return {
plugins: [
new PrerenderSPAPlugin({
staticDir: path.join(__dirname, "dist"),
// 对应自己的路由文件,比如a有参数,就需要写成 /a/param1。
routes: ["/", "/about", "/product"],
renderer: new Renderer({
inject: {
foo: "bar"
},
headless: false,
// 在 main.js 中 document.dispatchEvent(new Event('render-event')),两者的事件名称要对应上。
renderAfterDocumentEvent: "render-event"
})
})
]
};
}
};
main.js中
import Vue from "vue";
import App from "./App.vue";
import "./registerServiceWorker";
import router from "./router";
Vue.config.productionTip = false;
new Vue({
router,
mounted() {
document.dispatchEvent(new Event("render-event"));
},
render: (h) => h(App)
}).$mount("#app");
router.js,添加一些简单的页面
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Home",
component: Home
},
{
path: "/about",
name: "About",
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "about" */ "../views/About.vue")
},
{
path: "/admin",
name: "admin",
component: () =>
import(/* webpackChunkName: "admin" */ "../views/admin.vue")
},
{
path: "/product",
name: "product",
component: () =>
import(/* webpackChunkName: "product" */ "../views/product.vue")
}
];
const router = new VueRouter({
mode: "history",
base: process.env.BASE_URL,
routes
});
export default router;
打包后的效果
这里我为了区分出效果,路由里添加了一个admin.vue不做预渲染,about.vue做预渲染,打包后可以发现实现了预期的功能,about单独打包成了html文件,admin文件没有。另外说明一下预渲染的单页应用路由需要使用 History 模式而不是 Hash 模式。Hash 不会带到服务器,路由信息会丢失。
沃梦达教程
本文标题为:使用prerender-spa-plugin实现vue预渲染
基础教程推荐
猜你喜欢
- 在实战中可能碰到的几种ajax请求方法详解 2023-02-01
- HTML clearfix清除浮动讲解 2022-11-20
- Ajax+smarty技术实现无刷新分页 2022-12-15
- cocos creator游戏实现loading加载页面,游戏启动加载动画 2022-10-29
- Javascript Bootstrap的网格系统,导航栏和轮播详解 2023-08-11
- Ajax发送和接收请求 2022-12-15
- 关于Ajax跨域问题及解决方案详析 2023-02-23
- JS滚动到顶部踩坑解决记录 2023-07-10
- 使用ajax跨域调用springboot框架的api传输文件 2023-02-23
- uniapp开发微信小程序自定义顶部导航栏功能实例 2022-10-21