3
头图

foreword

In "An article that takes you to build a blog with VuePress + Github Pages" , we used VuePress to build a blog, and the final effect can be viewed: TypeScript Chinese document .

This article talks about JSON-LD in SEO.

JSON-LD

If we open any article of the Nuggets, such as this "VuePress Blog Optimization: Adding Vssue Comments" , and view the DOM elements, we can find such a script tag in the head:

It can also be seen on other platforms such as Sifu:

So what does this script with type application/ld+json mean? And what is its function?

This is the JSON-LD we are going to introduce today, full English: JavaScript Object Notation for Linked Data, official address: https://json-ld.org/ short, it is used to describe the type and The content is convenient for search engines to display.

For example, if we search for "Chocolate in a mug" on Google, we will see search results like this:

When we open the page, we can see that the content displayed by the search corresponds to the content in application/ld+json :

Add JSON-LD

If we also want to achieve such an effect to facilitate the display of search engines, what should we do?

The method of adding structured data to the page is very simple, just add a script like this to the page:

<script type="application/ld+json">
    // ...
</script>

For the specific content, please refer to "General Guide to Structured Data" provided by Google Search Center, because I wrote a specific article, so after referring to Article chapter , I decided to write the following attributes:

<script type="application/ld+json">
     {
      "@context": "https://schema.org",
      "@type": "Article",
      "headline": "这里填写标题",
      "image": [
        "https://ts.yayujs.com/icon-144x144.png"
       ],
      "datePublished": "2021-11-10T22:06:06.000Z",
      "dateModified": "2022-03-04T16:00:00.000Z",
      "author": [{
          "@type": "Person",
          "name": "冴羽",
          "url": "https://github.com/mqyqingfeng/Blog"
        }]
    }
</script>

VuePress implementation

After searching, I did not find any ready-made plug-ins. Since the title, release time, and update time of each page are different, that's it, then write a local plug-in to realize it.

In fact, the content to be implemented is very simple, that is, write a script script in the head when compiling. The content of the script depends on the properties of the page, but after all, I am using vuepress 1.x, and the implementation method is subject to tools, completely Look at what API the tool provides to implement, let's look directly at the final implementation:

vuepress-plugin-jsonld

Create a vuepress-plugin-jsonld folder in the .vuepress directory, then execute npm init to create package.json

Create index.js and write the code:

const { path } = require('@vuepress/shared-utils')

module.exports = options => ({
  name: 'vuepress-plugin-jsonld',
  enhanceAppFiles () {
    return [path.resolve(__dirname, 'enhanceAppFile.js')]
  },
  globalUIComponents: ['JSONLD']
})

Create enhanceAppFile.js and write the code:

import JSONLD from './JSONLD.vue'

export default ({ Vue, options }) => {
  Vue.component('JSONLD', JSONLD)
}

Create JSONLD.vue and write the code:

<template></template>

<script>
export default {
  created() {
    if (typeof this.$ssrContext !== "undefined") {
      this.$ssrContext.userHeadTags += 
      `<script type='application/ld+json'>
          {
            "@context": "https://schema.org",
            "@type": "Article",
            "headline": "${this.$page.title}",
            "url": "${'https://yayujs.com' + this.$page.path}",
            "image": [
              "https://ts.yayujs.com/icon-144x144.png"
              ],
            "datePublished": "${this.$page.frontmatter.date && (new Date(this.$page.frontmatter.date)).toISOString()}",
            "dateModified": "${this.$page.lastUpdated && (new Date(this.$page.lastUpdated)).toISOString()}",
            "author": [{
                "@type": "Person",
                "name": "冴羽",
                "url": "https://github.com/mqyqingfeng/Blog"
            }]
          }
      <\/script>`;
    }
  }
};
</script>

The reason why we can inject script content into all pages is because of the help of globalUIComponents :

You might want to inject some global UI and pin it somewhere in the page, like back-to-top, popup. In VuePress, a global UI is a Vue component.

config.js

Next we modify config.js:

module.exports = {
    title: 'title',
    description: 'description',
       plugins: [
      require('./vuepress-plugin-jsonld')
    ]
}

Note that we can't see it when we run it locally. We can close the deploy.sh command that is pushed to the remote, then compile it locally and check the output HTML:

verify

After publishing it online, we can verify it in the rich media search test provided by Google, open the URL, enter the page address, and you can see the scraped structured data:

If there are errors, warnings are also displayed here.

series of articles

The blog building series is the only series of practical tutorials I have written so far. It is expected to be about 20 articles, explaining how to use VuePress to build and optimize blogs, and deploy them to GitHub, Gitee, private servers and other platforms. This article is the 31st article, the address of the full series of articles: https://github.com/mqyqingfeng/Blog

WeChat: "mqyqingfeng", enter the readership of Xiangyu.

If there are any mistakes or inaccuracies, please be sure to correct me, thank you very much. If you like or have inspiration, welcome to star, which is also an encouragement to the author.


冴羽
9.3k 声望6.3k 粉丝

17 年开始写前端文章,至今 6 个系列,上百篇文章,全网千万阅读