Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change content of VuePress page via Plugin

I am trying to set up a plugin to change the content of a VuePress markdown file on the dev server and production build. According to documentation, I should be able to use the _content and _strippedContent that is available to me with the extendPageData

The following code is what I have set up in a plugin to do this.

module.exports = (options = {}, context) => ({
  extendPageData($page) {
    const {
      _filePath, // file's absolute path
      _computed, // access the client global computed mixins at build time, e.g _computed.$localePath.
      _content, // file's raw content string
      _strippedContent, // file's content string without frontmatter
      key, // page's unique hash key
      frontmatter, // page's frontmatter object
      regularPath, // current page's default link (follow the file hierarchy)
      path, // current page's real link (use regularPath when permalink does not exist)
    } = $page

    $page._content = "replaced"
    $page._strippedContent = "replaced"
  }
})

The best I can tell is that this code should work as it updates the $page._content however it is not showing testing but rather the original content.

I know that I am getting into this code as I can console.log from the file and it shows in the console.

I fear that $page._content is immutable and wonder if there is a way to do this kind of content swapping during dev or build

like image 891
bretterer Avatar asked Mar 07 '19 14:03

bretterer


1 Answers

The information in those page objects is used after the markdown has been compiled and during the Vue component rendering. The content is more there for reference and modifying it won't have the effect you are after.

This tripped me up as well.

All the markdown files are processed for inoformation, but then the actual compilation occurs through webpack. The general flow is:

.md -> markdown-loader -> vue-loader -> ...

My recommendation and what I have done is to create a custom webpack loader to modify the content before it goes through the VuePress markdown loader. I used this approach to run my markdown files through Nunjucks for templating pre-markdown compilation. It's increadibly easy to do this after you figure out the correct approach :) Here is a working approach:

config.js:

chainWebpack: config => {
    config.module
      .rule('md')
      .test(/\.md$/)
      .use(path.resolve(__dirname, './nunjucks'))
        .loader(path.resolve(__dirname, './nunjucks'))
        .end()
},

And then a simple loader can look like this(abridged):

module.exports = function(source) {   
    const rendered = nunjucks.renderString(source, config)
    return rendered
}
like image 69
Greg Avatar answered Nov 14 '22 23:11

Greg