configurationstatic-sitevuepressyaml-front-matter

Front-matter defaults in VuePress config


I'm trying to switch my documentation site from GitBook to Vuepress and got stuck with front-matter variables. In GitBook, you just add variables in the config and then use them anywhere on the page as {{ book.variable_name }}. In Vuepress, at glance, things seem to be trickier.

I need to configure several variables that are used across the whole site, so adding them to each page would be a complete nightmare. The documentation tells nothing about how to configure front-matter variables but has a link to the Jekyll site. On the Jekyll site, I found this article that is exactly what I want to achieve. The problem is that I have no idea how to use this info in config.

Any help is highly appreciated. I asked this question in the official repo but that didn't help.


Solution

  • To define some variables that you could access anywhere in your site, you can add them to your theme config.

    If you haven't already got one, create a config.js file at .vuepress/config.js.

    This file should export an object.

    You want to add a themeConfig: {} to this.

    Properties you set on the themeConfig object will be available throughout your site on $themeConfig.

    //- .vuepress/config.js
    
    module.exports = {
      themeConfig: {
        //- Define your variables here
        author: 'Name',
        foo: 'bar'
      }
    }
    
      {{ $themeConfig.author }} //- 'Name'
      {{ $themeConfig.foo }} //- 'bar
    

    You can also make this easy to override locally / per page, by using global computed functions. (This could also provide a cleaner way to access the variables)

    Adding an enhanceApp.js file in the same place as config.js, will give you access to the Vue instance - where you can define a mixin for all components.

    You can define some computed properties in this mixin that first check for a value in the pages frontmatter data and then fall back to the value set in the themeConfig. Allowing you to set some default values that can be locally overridden per page.

    //- .vuepress/enhanceApp.js
    
    export default ({ Vue }) => {
      Vue.mixin({
        computed: {
          author() {
            const { $themeConfig, $frontmatter } = this
            return $frontmatter.author || $themeConfig.author
          },
          foo() {
            const { $themeConfig, $frontmatter } = this
            return $frontmatter.foo || $themeConfig.foo
          }
        }
      })
    }
    
    
      {{ author }}  //- 'Name'
      {{ foo }} //- 'bar
    

    Vuepress config docs Vuepress app level enhancement