1.安装

npm install --save-dev prerender-spa-plugin

安装过程中,会下载puppeteer

2.配置build/webpack.prod.conf.js
基本

const path = require('path')
const PrerenderSPAPlugin = require('prerender-spa-plugin')

module.exports = {
  plugins: [
    ...
    new PrerenderSPAPlugin({
      // Required - The path to the webpack-outputted app to prerender.
      staticDir: path.join(__dirname, '../dist'),
      // Required - Routes to render.
      routes: [ '/', '/about' ],
    })
  ]
}

高级

const PrerenderSPAPlugin = require('prerender-spa-plugin')
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer

module.exports = {
  plugins: [
    ...
    new PrerenderSPAPlugin({
      staticDir: path.join(__dirname, '../dist'),
      routes: [ '/', '/about' ],
      renderer: new Renderer({
        inject: {
          foo: 'bar'
        },
        headless: false,
        // renderAfterDocumentEvent: 'render-event',
        renderAfterTime: 5000
      })
    })
  ]
}

如果设置renderAfterDocumentEvent需要修改main.js文件

new Vue({
  el: '#app',
  store,
  router,
  components: { App },
  template: '<App/>',
  render: h => h(App),
  mounted () {
    // You'll need this for renderAfterDocumentEvent.
    document.dispatchEvent(new Event('render-event'))
  }
})

1.打包后console报错Uncaught ReferenceError: webpackJsonp is not defined
处理:头部js文件async=""修改为defer=""

相关链接:https://github.com/chrisvfritz/prerender-spa-plugin

作者 铁血 汉子 2018年12月14日
2024/12/22/01:58:16pm 2018/12/14/7:24:56
0 4262