3
头图

foreword

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

In the process of building the blog, we have, for practical needs, in "VuePress blog optimization of expansion Markdown syntax" in explaining how to write a markdown-it plug-in, but also in "Markdown-IT principles to resolve" are explained markdown-it In this article, we will explain the specific actual code to help you write plug-ins better.

markdown-it-inline

markdown-it the authors provide markdown-it-inine for easy modification inline tokens. For example, if we add target="_blank" to all links, normally you would write:

// Remember old renderer, if overridden, or proxy to default renderer
var defaultRender = md.renderer.rules.link_open || function(tokens, idx, options, env, self) {
  return self.renderToken(tokens, idx, options);
};

md.renderer.rules.link_open = function (tokens, idx, options, env, self) {
  // If you are sure other plugins can't add `target` - drop check below
  var aIndex = tokens[idx].attrIndex('target');

  if (aIndex < 0) {
    tokens[idx].attrPush(['target', '_blank']); // add new attribute
  } else {
    tokens[idx].attrs[aIndex][1] = '_blank';    // replace value of existing attr
  }

  // pass token to default renderer.
  return defaultRender(tokens, idx, options, env, self);
};

After using markdown-it-for-inline :

var iterator = require('markdown-it-for-inline');

var md = require('markdown-it')()
            .use(iterator, 'url_new_win', 'link_open', function (tokens, idx) {
              var aIndex = tokens[idx].attrIndex('target');

              if (aIndex < 0) {
                tokens[idx].attrPush(['target', '_blank']);
              } else {
                tokens[idx].attrs[aIndex][1] = '_blank';
              }
            });

If we want to replace a certain text, we can also use markdown-it-for-inline :

var iterator = require('markdown-it-for-inline');

// plugin params are:
//
// - rule name (should be unique)
// - token type to apply
// - function
//
var md = require('markdown-it')()
            .use(iterator, 'foo_replace', 'text', function (tokens, idx) {
              tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar');
            });

markdown-it-container

Plugin for creating block-level custom containers for markdown-it markdown parser.

The author of markdown-it also provides markdown-it-container for quickly creating block-level custom containers.

With this plugin, you can use markdown syntax like this:

::: spoiler click me
*content*
:::

Note that ::: is the syntax defined by the plugin, it will take out ::: , in this example it is warning , and provide a method to customize the rendering result:

var md = require('markdown-it')();

md.use(require('markdown-it-container'), 'spoiler', {

  validate: function(params) {
    return params.trim().match(/^spoiler\s+(.*)$/);
  },

  render: function (tokens, idx) {
    // 通过 tokens[idx].info.trim() 取出 'click me' 字符串
    var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);

    // 开始标签的 nesting 为 1,结束标签的 nesting 为 -1
    if (tokens[idx].nesting === 1) {
      // 开始标签
      return '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n';
    } else {
      // 结束标签
      return '</details>\n';
    }
  }
});

The final rendered result is:

<details><summary>click me</summary>
<p><em>content</em></p>
</details>

Like VuePress provides custom container :

In fact, with markdown-it-container implemented, its implementation source as:

const container = require('markdown-it-container')

module.exports = md => {
  md
    .use(...createContainer('tip', 'TIP'))
    .use(...createContainer('warning', 'WARNING'))
    .use(...createContainer('danger', 'WARNING'))
        // ...
}

function createContainer (klass, defaultTitle) {
  return [container, klass, {
    render (tokens, idx) {
      const token = tokens[idx]
      const info = token.info.trim().slice(klass.length).trim()
      if (token.nesting === 1) {
        return `<div class="${klass} custom-block"><p class="custom-block-title">${info || defaultTitle}</p>\n`
      } else {
        return `</div>\n`
      }
    }
  }]
}

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 18th article, the address of the full series of articles: https://github.com/mqyqingfeng/Blog

WeChat: "mqyqingfeng", add me to the only readership of Xianyu.

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 个系列,上百篇文章,全网千万阅读