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? A brief analysis of the usage of prerender-spa-plugin

青灯夜游
青灯夜游forward
2022-02-07 18:04:025132browse

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!

How to pre-render web pages in Vue? A brief analysis of the usage of prerender-spa-plugin

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.htmlInternal 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.

How to pre-render web pages in Vue? A brief analysis of the usage of prerender-spa-plugin

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, because

prerender-spa-plugin will install a Chromium, so the installation will take a long time.

How to pre-render web pages in Vue? A brief analysis of the usage of prerender-spa-plugin

#Of course, this dependency is only used when packaging. Therefore, a better installation method should be:

npm i prerender-spa-plugin -D

Project reference

Now, 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 in

App.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 to

prerender-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 headless attribute, 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.
And the

routes array contains the routing addresses that need to be pre-rendered.

How to pre-render web pages in Vue? A brief analysis of the usage of prerender-spa-plugin

Of course, for more optional parameters, you can also refer to the official documentation:

How to pre-render web pages in Vue? A brief analysis of the usage of prerender-spa-plugin

staticDir needs to point to the compiled output folder.

Packaging the project

After that, we can package the project:

npm run build

The effect after packaging:

How to pre-render web pages in Vue? A brief analysis of the usage of prerender-spa-plugin

Take a look at the pre-rendered page:

How to pre-render web pages in Vue? A brief analysis of the usage of prerender-spa-plugin

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/;
}

给大家展示三种配置,按需设置哦。

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!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete