markdown-it 插件如何写(三)

冴羽
• 阅读 1105

前言

《一篇带你用 VuePress + Github Pages 搭建博客》中,我们使用 VuePress 搭建了一个博客,最终的效果查看:TypeScript 中文文档

在搭建博客的过程中,我们出于实际的需求,在《VuePress 博客优化之拓展 Markdown 语法》中讲解了如何写一个 markdown-it插件,又在 《markdown-it 原理解析》中讲解了 markdown-it的执行原理,本篇我们将讲解具体的实战代码,帮助大家更好的写插件。

markdown-it-inline

markdown-it 的作者提供了 markdown-it-inine 用于方便修改 inline tokens 。举个例子,如果我们给所有的链接添加 target="_blank",正常你需要这样写:

// 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);
};

使用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';
              }
            });

如果我们要替换掉某个文字,也可以使用 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.

markdown-it 的作者同样提供了 markdown-it-container 用于快速创建块级自定义容器。

有了这个插件,你可以这样使用 markdown 语法:

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

注意这其中的 ::: 是插件定义的语法,它会取出 ::: 后的字符,在这个例子中是 warning,并提供方法自定义渲染结果:

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';
    }
  }
});

最终渲染的结果为:

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

像 VuePress 提供了自定义容器

markdown-it 插件如何写(三)

其实就是用 markdown-it-container 实现的,其实现源码为:

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`
      }
    }
  }]
}

系列文章

博客搭建系列是我至今写的唯一一个偏实战的系列教程,预计 20 篇左右,讲解如何使用 VuePress 搭建、优化博客,并部署到 GitHub、Gitee、私有服务器等平台。本篇为第 18 篇,全系列文章地址:https://github.com/mqyqingfeng/Blog

微信:「mqyqingfeng」,加我进冴羽唯一的读者群。

如果有错误或者不严谨的地方,请务必给予指正,十分感谢。如果喜欢或者有所启发,欢迎 star,对作者也是一种鼓励。

点赞
收藏
评论区
推荐文章
冴羽 冴羽
2年前
有的时候我觉得我不会 Markdown
前言在中,我们使用VuePress搭建了一个博客,最终的效果查看:。在优化博客的过程中,因为需要写markdownit插件,翻了下markdown的,突然发现对Markdown还远不够了解:软换行(Softlinebreaks)换行符不在行内代码或HTML标签内,前面没有两个或以上的空格,将解析为软换行(Softlinebr
冴羽 冴羽
2年前
从零实现一个 VuePress 插件
前言在中,我们使用VuePress搭建了一个博客,最终的效果查看:。但在搭建VuePress博客的过程中,也并不是所有的插件都能满足需求,所以本篇我们以实现一个代码复制插件为例,教大家如何从零实现一个VuePress插件。本地开发开发插件第一个要解决的问题就是如何本地开发,我们查看VuePress1.0官方文档的「」章节,并没有找到解决
冴羽 冴羽
2年前
markdown-it 插件如何写(二)
前言在中,我们使用VuePress搭建了一个博客,最终的效果查看:。在搭建博客的过程中,我们出于实际的需求,在中讲解了如何写一个markdownit插件,又在中讲解了markdownit的执行原理,本篇我们将讲解具体的实战代码,帮助大家更好的写插件。Parsemarkdownit的渲染过程分为两部分,Parse和Render,如果我们要实现
冴羽 冴羽
2年前
VuePress 博客优化之增加 Vssue 评论功能
前言在中,我们使用VuePress搭建了一个博客,最终的效果查看:。本篇讲讲如何使用Vssue快速的实现评论功能。主题内置因为我用的是vuepressthemereco主题,主题内置评论插件@vuepressreco/vuepressplugincomments,可以根据自己的喜好选择Valine或者Vssue。那我们来介绍下Vss
冴羽 冴羽
2年前
VuePress 博客优化之 last updated 最后更新时间如何设置
前言在中,我们使用VuePress搭建了一个博客,但是浏览最终搭建的站点:,我们会发现,在每篇文章的底部,并没有像VuePress官方文档那样,出现最后更新的时间:这篇我们来探究下如何实现最后更新时间。官方自带查阅VuePress的,我们可以知道,VuePress自带显示最后更新时间的插件,在默认主题下,无需安装本插件,因为VuePre
冴羽 冴羽
2年前
VuePress 博客优化之增加 Valine 评论功能
前言在中,我们使用VuePress搭建了一个博客,最终的效果查看:。本篇讲讲如何使用Valine快速的实现评论功能。主题内置因为我用的是vuepressthemereco主题,主题内置评论插件@vuepressreco/vuepressplugincomments,可以根据自己的喜好选择Valine或者Vssue。本篇讲讲使用Val
冴羽 冴羽
2年前
markdown-it 插件如何写(一)
前言在中,我们使用VuePress搭建了一个博客,最终的效果查看:。在搭建博客的过程中,我们出于实际的需求,在中讲解了如何写一个markdownit插件,又在中讲解了markdownit的执行原理,本篇我们将讲解具体的实战代码,帮助大家更好的写插件。renderermarkdownit的渲染过程分为两部分,Parse和Render,如果我们
冴羽 冴羽
2年前
VuePress 博客之 SEO 优化(三)标题、链接优化
前言在中,我们使用VuePress搭建了一个博客,最终的效果查看:。本篇讲讲SEO中的一些细节优化。1.设置全局的title、description、keywordsjavascript//config.jsmodule.exportstitle:"title",description:'description',
冴羽 冴羽
2年前
搭建 VuePress 博客,你可能会用到的一些插件
前言在中,我们使用VuePress搭建了一个博客,最终的效果查看:。为了丰富站点的功能,我们可以直接使用一些现有的插件,本篇我们讲讲一些常用的插件。1.公告栏弹窗插件地址:安装:bashyarnadd@vuepressreco/vuepresspluginbulletinpopoverD使用:javascriptplugins:注意事项:查
冴羽 冴羽
2年前
Markdown-it 原理解析
前言在中,我们使用VuePress搭建了一个博客,最终的效果查看:。在搭建博客的过程中,我们出于实际的需求,在中讲解了如何写一个markdownit插件,本篇我们将深入markdownit的源码,讲解markdownit的执行原理,旨在让大家对markdownit有更加深入的理解。介绍引用的介绍:Markdownparserdoner
冴羽
冴羽
Lv1
男 · 淘宝 · 前端工程师
GitHub 26K Star 的博客: https://github.com/mqyqingfeng/Blog
文章
32
粉丝
15
获赞
67