沃梦达 / IT编程 / 前端开发 / 正文

使用prerender-spa-plugin实现vue预渲染

初始化创建一个项目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预渲染