vue预渲染prerender-spa-plugin-next 和 vue-meta-info

淳于烈
2023-12-01

prerender-spa-plugin-next实现方法

const { defineConfig } = require('@vue/cli-service')
const PrerenderSPAPlugin = require("prerender-spa-plugin-next");
const renderer = require("@prerenderer/renderer-puppeteer");
const path = require('path');
module.exports = defineConfig({
  // 添加下面的配置
  configureWebpack: config => {
    if (process.env.NODE_ENV === "production") {
      config.mode = "production";
      config.performance = {
        maxEntrypointSize: 10000000,
        maxAssetSize: 30000000,
      };
      config.plugins.push(
        new PrerenderSPAPlugin({
          routes: ["/home"],
          rendererOptions: {
            renderAfterDocumentEvent: "render-event",
            inject: {},
            timeout: 10000,
          },
          // 可选
          renderer,
          postProcess: function (context) {
            var titles = {
              "/home": "首页"
            };
            context.html = context.html.replace(
              /<title>[^<]*<\/title>/i,
              "<title>" + titles[context.route] + "</title>"
            );
          },
          renderOptions: {
            renderAfterDocumentEvent: "prerender",
          },
        })
      );
    }
  },
  transpileDependencies: true,
  lintOnSave: false,
  devServer: {
    proxy: { //配置跨域
      '/api': {
        target: '', //填写请求的目标地址
        changOrigin: true, //允许跨域
        pathRewrite: {
          '^/api': '' //请求的时候使用这个api就可以
        },
      }
    }
  },
})

main.js

```javascript
new Vue({
  router,
  store,
  mounted() {
    document.dispatchEvent(new Event('render-event'))
},
  render: h => h(App),
  
}).$mount('#app')

路由渲染方式history

const router = new VueRouter({
  mode: 'history',
  routes,
})
引入vue-meta-info
```javascript
import MetaInfo from 'vue-meta-info'

在使用预渲染处理的页面

  name: 'MainView',
  metaInfo: {
    title: '首页',
    meta: [
      {
        name: 'keywords',
        content: '关键词'
      }
    ]
  },

打包后,生成home文件夹,成功

 类似资料: