使用Vuepress自动生成markdown的目录时,一旦标题有数字时便无法跳转的问题解决

问题描述

 最近在用vuepress写网页文档的时候发现了一个问题,就是我用markdown书写的标题中如果有类似  1.2 XXX  的标题时,当使用官方文档给出的:

[[toc]]

自动生成目录时,最终生成的网页,含有数字的标题是无法跳转到相应位置的。

问题分析

查看官方开发文档后发现,这跟vuepress的默认配置有关,从如图1所示markdown.slugify函数可以看到,我们需要修改其配置。

markdown.slugify函数
图1  markdown.slugify函数

点击图中的source,跳转到GitHub的工程页面,可以看到如下的代码段:

// string.js slugify drops non ascii chars so we have to
// use a custom implementation here
// @ts-ignore
import { remove as removeDiacritics } from 'diacritics'

// eslint-disable-next-line no-control-regex
const rControl = /[\u0000-\u001f]/g
const rSpecial = /[\s~`!@#$%^&*()\-_+=[\]{}|\\;:"'<>,.?/]+/g

export = function slugify (str: string): string {
  return removeDiacritics(str)
  // Remove control characters
    .replace(rControl, '')
    // Replace special characters
    .replace(rSpecial, '-')
    // Remove continous separators
    .replace(/\-{2,}/g, '-')
    // Remove prefixing and trailing separtors
    .replace(/^\-+|\-+$/g, '')
    // ensure it doesn't start with a number (#121)
    .replace(/^(\d)/, '_$1')
    // lowercase
    .toLowerCase()
}

看到了其中有一句ensure it doesn't start with a number (#121),可以知道这就是问题所在:

    // ensure it doesn't start with a number (#121)
    .replace(/^(\d)/, '_$1')

我们的标题数字被这句代码替换掉了,导致最终的链接根本没有指向标题,故无法跳转。

问题解决

根据GitHub页面上的配置路径,找到自己安装的vuepress模块的配置路径,我的路径是:

D:\my_program\nodejs\node_global\node_modules\vuepress\node_modules\@vuepress\shared-utils\lib\slugify.js

打开 slugify.js 文件,并将上述的代码段注释掉,问题即可解决。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值