vue 预渲染 prerender-spa-plugin

预渲染模式
预渲染 prerender-spa-plugin 配置生成多页面,解决首屏白屏问题,提升用户体验。同时配合 vue-meta-info 可以生成 titlemeta标签,可解决SPA页面的SEO痛点。

  • prerender-spa-plugin 使用方法
    1. 安装 prerender-spa-plugin
      npm i prerender-spa-plugin --save
    2. 使用
      我的项目是用 vue-cli3进行的搭建,在 vue.config.js 文件里进行如下操作。
    const PrerenderSPAPlugin = require('prerender-spa-plugin');
    const Renderer = PrerenderSPAPlugin.PuppeteerRenderer;
    const path = require('path');
    
    module.exports = {
      configureWebpack: config => {
        config.plugins.push(
          new PrerenderSPAPlugin({
            staticDir: path.join(__dirname, 'dist'),
            // 需要进行预渲染的路由路径 我这里做的是首页
            routes: ['/'],
            // html文件压缩
            minify: {
                minifyCSS: true, // css压缩
                removeComments: true // 移除注释
            },
            renderer: new Renderer({
                // Optional - The name of the property to add to the window object with the contents of `inject`.
                injectProperty: '__PRERENDER_INJECTED',
                // Optional - Any values you'd like your app to have access to via `window.injectProperty`.
                inject: {},
                // 在 main.js 中 new Vue({ mounted () {document.dispatchEvent(new Event('render-event'))}}),两者的事件名称要对应上。
                // renderAfterDocumentEvent: 'render-event'
            })
          })
        )
      }
    };
    
    1. 重新打包后访问项目就能看到效果

注意:官方文档上 路由模式必须为 history 。如果不设置history模式,也能运行和生成文件,每个index.html文件的内容都会是一样的。所以必须使用 history模式

你可能感兴趣的:(vue 预渲染 prerender-spa-plugin)