Use a background

Recently, the company has to do SEO optimization for the old project built based on Vue-CLI3.0, and the route is hash mode; The cost of server rendering is very high. After reading some articles, I decided to try pre-rendering and use vue-meta-info to customize meta information to achieve the desired effect.

Modified content

1. Routing mode

  • Change the routing mode to history mode and remove the # from the URL
const router = new VueRouter({
  mode: 'history',
  routes: [...]
})
Copy the code
  • Lazy route loading, with pre-rendering better on demand loading
{
    path: "/about",
    name: "About",
    component: () =>
      import(/* webpackChunkName: "about"* /".. /views/About.vue")}Copy the code
Js ├── app.7be39401.js ├── chunk-vendors.9cd40e36.js
Copy the code
  • Server configuration overwrites pages returned without static resources, avoiding direct access or refreshing 404

The pre-rendered page access path points to the index. HTML in its corresponding directory, or in other cases directly points to the main entry index. HTML in the root directory of the package output.

/** * Create local service */ http.createserver ((req, res)) => {const filePath = getFilePath(req); const indexFilePath = path.join(__dirname,"/dist/index.html");
    const exists = fs.existsSync(filePath);
    const data = fs.readFileSync(exists ? filePath : indexFilePath);
    writeHead(res, filePath);
    res.end(data);
  })
  .listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/ `); });Copy the code
Dist ├ ─ ─ the favicon. Ico ├ ─ ─ home │ └ ─ ─ index. The HTML < - http://localhost:8080/home page returns the pre-rendered ├ ─ ─ index. The HTML < -- http://localhost:8080/about to return to the candidate resources └ ─ ─ the staticCopy the code

2. The prerender – spa – the plugin to use

  • Install dependencies
NPM install prerender - spa - plugin - save - dev or use mirror installation or CNPM registry at https://registry.npm.taobao.orgCopy the code
  • Add the vue.config.js configuration
const path = require("path");
const PrerenderSpaPlugin = require("prerender-spa-plugin");
const isProduction = process.env.NODE_ENV === "production";

module.exports = {
  publicPath: "/",
  outputDir: "dist",
  assetsDir: "static",
  productionSourceMap: false,
  configureWebpack: config => {
    ifNew PrerenderSpaPlugin({// static resource path: path.join(__dirname,"dist"), // pre-render routes: ["/home"]})); }}};Copy the code
  • The dist directory is generated after build with the following structure:
Dist ├── favicon.ico ├── home │ ├─ index.html <-- Html.pdf ├── index.html <-- html.pdfCopy the code

3. The vue meta – use the info

  • Install dependencies
 npm install vue-meta-info --save-dev
Copy the code
  • Global registration
import Vue from 'vue'
import MetaInfo from 'vue-meta-info'

Vue.use(MetaInfo)
Copy the code
  • Component, and custom meta information is also written to the page during pre-rendering
<template>
  ...
</template>

<script>
  export default {
    metaInfo: {
      // set a title
      title: 'Home', / /set meta
      meta: [{                
        name: 'keyword',
        content: 'My Example Keyword'}]. / /set link
      link: [{                 
        rel: 'asstes',
        href: 'https://xxx.com/'
      }]
    }
  }
</script>
Copy the code

4. Try the effect

Full example address

The command is built into the sample project, and after packaging the output dist directory, the local service is automatically run for preview.

conclusion

  • Compared to server rendering, simple and easy to use
  • Suitable for pages with a small number of static pages
  • There will be a blank period for the asynchronous loading of the pre-rendered page data, and the pre-rendered part will be loaded first. At this point can be appropriate to add the loading state or skeleton screen to avoid embarrassment