初始化创建一个项目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-14
- 1 Vue - 简介 2023-10-08
- 关于 html:如何从 css 表中删除边距和填充 2022-09-21
- jsPlumb+vue创建字段映射关系 2023-10-08
- 深入浅析AjaxFileUpload实现单个文件的 Ajax 文件上传库 2022-12-15
- 基于CORS实现WebApi Ajax 跨域请求解决方法 2023-02-14
- JS实现左侧菜单工具栏 2022-08-31
- layui数据表格以及传数据方式 2022-12-13
- javascript 判断当前浏览器版本并判断ie版本 2023-08-08
- vue keep-alive 2023-10-08