Example of pre-rendering method for Vue single page application

Example of pre-rendering method for Vue single page application

Preface

Projects packaged with vue-cli are generally spa projects. As we all know, single-page applications are not conducive to SEO. There are two solutions: ssr (server-side rendering) and pre-rendering. Here we only discuss pre-rendering.

vue-cli 2.0 version

Install

npm install prerender-spa-plugin --save

webpack.prod.conf.js add some code

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

plugins:[
	// Configure PrerenderSPAPlugin
    new PrerenderSPAPlugin({
      // The path of the generated file can also be consistent with the path packaged by webpakc.
      staticDir: path.join(__dirname, '../dist'),
      
      // Corresponding to your own routing file, for example, if index has parameters, you need to write it as /index/param1.
      routes: ['/', '/report','/genius','/index/param1'],
      // Must be written, if this section is not configured, precompilation will not be performedrenderer: new Renderer({
          inject: {
            foo: 'bar'
          },
          headless: false,
          // In main.js, document.dispatchEvent(new Event('render-event')), the event names of the two should correspond.
          renderAfterDocumentEvent: 'render-event'
      })
    })
]

Add in main.js

new Vue({
  el: '#pingce',
  router,
  store,
  components: { App },
  template: '<App/>',
  // Add mounted, otherwise precompilation will not be executed mounted () {
    document.dispatchEvent(new Event('render-event'))
  }
})

Set mode: "history" in router.js

Run npm run build and check whether there is a folder corresponding to each route name in the generated dist directory. Then find the index.html in the directory and open it with IDE to see if the file contains the content that the file should have.

Each route you configure will generate a folder, and then an index.html will be generated under each folder.

vue-cli 3.0 version

The 3.0 cli looks much simpler, removing the 2.0 build and config directories. So how do we modify the webpack configuration?

Create vue.config.js in the root directory and make your configuration.

Install

npm install prerender-spa-plugin --save

Add in vue-config.js

const PrerenderSPAPlugin = require('prerender-spa-plugin'); // Import plugin const Renderer = PrerenderSPAPlugin.PuppeteerRenderer;
const path = require('path');
module.exports = {
    configureWebpack: config => {
        if (process.env.NODE_ENV !== 'production') return;
        return {
            plugins: [
                new PrerenderSPAPlugin({
                    // The path of the generated file can also be consistent with the path packaged by webpakc.
                    // This directory can only have one level. If the directory level is greater than one level, there will be no error prompt during generation, and it will just get stuck during pre-rendering.
                    staticDir: path.join(__dirname,'dist'),
                    // Corresponding to your own routing file, for example, if about has parameters, you need to write it as /about/param1.
                    routes: ['/', '/product', '/about'],
                    //Must configure otherwise precompilation will not be performedrenderer: new Renderer({
                        inject: {
                            foo: 'bar'
                        },
                        headless: false,
                        // In main.js, document.dispatchEvent(new Event('render-event')), the event names of the two should correspond.
                        renderAfterDocumentEvent: 'render-event'
                    })
                }),
            ],
        };
    }
}

Add in main.js

new Vue({
  router,
  store,
  render: h => h(App),
  // The name of renderAfterDocumentEvent in vue-config.js: 'render-event' must correspond to mounted () {
    document.dispatchEvent(new Event('render-event'))
  }
}).$mount('#app')

Set mode: "history" in router.js

Run npm run build and check whether there is a folder corresponding to each route name in the generated dist directory.

Summarize

1. It is best to use history mode for routing. You can also run the generated file without using it, but the content of each index.html file is the same.

2. The settings in 3.0 are roughly the same as those in 2.0, but there are a few places that need attention.

In 2.0, set staticDir: path.join(__dirname,'../dist')

In 3.0, set staticDir: path.join(__dirname,'dist')

If these two settings are wrong, running npm run build will report an error.

If you want to set the title and meta information of each page, it is recommended to use [vue-meta-info]

This is the end of this article about pre-rendering of Vue single-page applications. For more relevant Vue single-page application pre-rendering content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • vue-cli single page pre-rendering seo-prerender-spa-plugin operation

<<:  Detailed graphic tutorial on installing centos7 virtual machine in Virtualbox

>>:  Web page creation for beginners: Learn to use HTML's hyperlink A tag

Recommend

Detailed explanation of how to manually deploy a remote MySQL database in Linux

1. Install mysql Run the following command to upd...

Docker-compose quickly builds steps for Docker private warehouse

Create docker-compose.yml and fill in the followi...

Example of how rem is adapted for mobile devices

Preface Review and summary of mobile terminal rem...

WeChat applet to determine whether the mobile phone number is legal example code

Table of contents Scenario Effect Code Summarize ...

Summary of 10 must-see JavaScript interview questions (recommended)

1.This points to 1. Who calls whom? example: func...

Reasons for the sudden drop in MySQL performance

Sometimes you may encounter a situation where a S...

How to run commands on a remote Linux system via SSH

Sometimes we may need to run some commands on a r...

Implement MySQL read-write separation and load balancing based on OneProxy

Introduction Part 1: Written at the beginning One...

Teach you how to build a react+antd project from scratch

The previous articles were all my own learning lo...

Teach you a trick to achieve text comparison in Linux

Preface In the process of writing code, we will i...

Summary of ways to implement single sign-on in Vue

The project has been suspended recently, and the ...