2024年12月07日 建站教程
步骤一:安装prerender-spa-plugin插件
npm install prerender-spa-plugin -D
步骤二:webpack.prod.conf.js新增以下代码
const path = require('path'); const PrerenderSPAPlugin = require('prerender-spa-plugin'); const Renderer = PrerenderSPAPlugin.PuppeteerRenderer; module.exports = { plugins: [new PrerenderSPAPlugin({ staticDir: path.join(__dirname, '../dist'), // 需要预渲染的路由 routes: [ '/', '/about', '/contact' ], renderer: new Renderer({ ignoreJSErrors: true, inject: { foo: 'bar' }, headless: true, renderAfterTime: 5000 }) })] }
注意事项:很多人会掉入headless
的坑,如果设置为false
打包的时候会报以下错误!
ERROR in [prerender-spa-plugin] Unable to prerender all routes!
步骤三:打开router/index.js文件修改一下代码
const router = new VueRouter({ mode: "history", base: process.env.BASE_URL, routes, // 预渲染,这是重点 mounted() { document.dispatchEvent(new Event('custom-render-trigger')) } });
本文链接:http://so.lmcjl.com/news/19147/