Home >Web Front-end >Vue.js >How to pre-render web pages in Vue? A brief analysis of the usage of prerender-spa-plugin
How to pre-render web pages in Vue? This article will introduce to you how Vue uses prerender-spa-plugin to pre-render web pages. I hope it will be helpful to you!
Normally, the Vue project is a single-page project, that is, the rendered project has only one index.html
. [Related recommendations: vue.js video tutorial]
The shortcomings of this are obvious:
try_files $uri $ uri/ /index.html
Internal redirection, the page can be accessed through routing. And pre-rendering is to render the original single index.html
into multiple directories, and each directory has another index.html
. This eliminates the need for internal redirection access routes and is more conducive to search engine inclusion.
This pre-rendering uses prerender-spa-plugin for pre-rendering.
Its main principle is to start the browser, grab the HTML after rendering is completed, and then create a directory and save it as index.html
.
Note:
##Installation
First, we use npm to install:npm i prerender-spa-plugin
Need to pay attention, because#Of course, this dependency is only used when packaging. Therefore, a better installation method should be:prerender-spa-plugin
will install a Chromium, so the installation will take a long time.
npm i prerender-spa-plugin -DProject referenceNow, let’s come to the project reference. The method of use is very simple, and it is convenient to append in two places:
App.vue
First , we add a trigger event inApp.vue:
mounted() { document.dispatchEvent(new Event('render-event')) }Adding this trigger will automatically trigger when subsequent packaging is completed, and rendering will be completed.
vue.config.js
According toprerender-spa-plugin project documentation:
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', '/some/deep/nested/route' ], }) ] }At the same time, some advanced uses need to introduce
PuppeteerRenderer for customization. So, my own
vue.config.js configuration:
module.exports = { …… chainWebpack: config => { if (process.env.NODE_ENV == "development") { …… } if (process.env.NODE_ENV == "production") { config.plugin("PrerenderSPAPlugin").use('prerender-spa-plugin', [ { staticDir: path.join(__dirname, 'dist'), routes: [ '/', '/processIMG', '/statisticsChars', '/generatePWD', '/calculateTheDate', '/randomNumber', '/textBase64', '/curl', '/mcstatus', '/gh', '/about', '/mdv' ], renderer: new PuppeteerRenderer({ headless: false, executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', // 对应App.vue renderAfterDocumentEvent: 'render-event', }), }]) ]) } }I use chain functions. The advantage of this is that it makes it easier for me to make functional judgments such as
if-else.
Among them, the
renderer attribute:
: This is Chrome’s
headless attribute, which is commonly used for Debug. For more information, please refer to:
Google Chrome
: Redirect browser address; I use the Chrome browser that comes with my computer for redirection here. (Optional, you can not add it directly, Chromium will be called by default)
: Needs to be the same event name as document.dispatchEvent(new Event('render-event')) in App.vue To correspond.
routes array contains the routing addresses that need to be pre-rendered.
staticDir needs to point to the compiled output folder.
npm run buildThe effect after packaging: Take a look at the pre-rendered page: Because I have components that use Vue-meta, the pre-rendered files also have meta attributes.
如果你也想用Vue-meta组件配合
prerender-spa-plugin
,可以参考文章:https://juejin.cn/post/7056972997894094861
需要注意,如果出现什么错误,可以尝试:
# 删除项目node_modules rm -rf node_modules # 重新安装 npm install
这样的文件,就可以进行部署了。
我们使用Nginx进行部署,上次到Nginx Web文件夹内,修改config
文件,就不需要:
location / { try_files $uri $uri/ /index.html; }
来实现内部重定向了。因为有真实的目录,可以去掉。
但是,数据代理,最好使用Nginx来实现。比如,开发环境,数据代理:
config.devServer.proxy({ '/dataApiJava': { target: JavaBaseURL, pathRewrite: {'^/dataApiJava': ""}, ws: true, changeOrigin: true }, '/dataApiPython': { target: PythonBaseURL, pathRewrite: {'^/dataApiPython': ""}, ws: true, changeOrigin: true }, '/ghs': { target: GithubSpeedURL, pathRewrite: {'^/ghs': ""}, ws: true, changeOrigin: true } } )
对应的Nginx配置,可以这样写:
location /dataApiPython/{ proxy_pass http://127.0.0.1:8099/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header REMOTE-HOST $remote_addr; add_header X-Cache $upstream_cache_status; } location /dataApiJava/ { proxy_ssl_server_name on; proxy_pass https://…….cn/; } location /ghs/ { proxy_ssl_server_name on; proxy_pass https://……/gh/; }
给大家展示三种配置,按需设置哦。
到此,我们的前端预渲染就完成了。这样SEO好。但是对比SSR,还是优点欠缺。好处就是部署和配置方便,坏处就是构建麻烦,如果你页面有几十个路由需要预渲染,那么prerender-spa-plugin渲染起来就没SSR方便了。
改天有机会和大家分享分享SSR吧,真不错,又挖一个坑。
另外,是不是有小伙伴好奇,我截图里出现的CompressionPlugin
属性?其实是gz压缩啦。有机会和大家分享,使用compression-webpack-plugin
来优化项目。
更多编程相关知识,请访问:编程入门!!
The above is the detailed content of How to pre-render web pages in Vue? A brief analysis of the usage of prerender-spa-plugin. For more information, please follow other related articles on the PHP Chinese website!