


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!
Pre-rendering
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:
- To deploy to Nginx, you need to do
try_files $uri $ uri/ /index.html
Internal redirection, the page can be accessed through routing. - SEO is not friendly and the search engine indexing effect is not good.
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.
prerender-spa-plugin
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:
- The official website currently only has Vue2.x Demo, which actually supports Vue3 (this demonstration also uses Vue3)
- Although the most recent one The released version is in 2018 (a new version should be released recently), but it has been maintained and can be used.
##Installation
First, we use npm to install:npm i prerender-spa-plugin
Need to pay attention, becauseprerender-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
- vue.config.js
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:
- headless
: This is Chrome’s
headlessattribute, which is commonly used for Debug. For more information, please refer to:
Google Chrome - executablePath
: 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)
- renderAfterDocumentEvent
: 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:
如果你也想用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/; }
给大家展示三种配置,按需设置哦。
END
到此,我们的前端预渲染就完成了。这样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!

Vue.js' role in web development is to act as a progressive JavaScript framework that simplifies the development process and improves efficiency. 1) It enables developers to focus on business logic through responsive data binding and component development. 2) The working principle of Vue.js relies on responsive systems and virtual DOM to optimize performance. 3) In actual projects, it is common practice to use Vuex to manage global state and optimize data responsiveness.

Vue.js is a progressive JavaScript framework released by You Yuxi in 2014 to build a user interface. Its core advantages include: 1. Responsive data binding, automatic update view of data changes; 2. Component development, the UI can be split into independent and reusable components.

Netflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.

Netflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version
Visual web development tools