How to change Markdown link relative path as preprocessing of gatsby-transformer-remark

有些话、适合烂在心里 提交于 2020-07-18 21:16:32

问题


I am developping a static blog using Gatsby. It use gatsby-transformer-remark and gatsby-plugin-i18n plugin to support multiple languages.

I am managing the articles in the GitHub repository as follows.

  • /blog
    • /2017
      • /06
        • 01-foo.en.md
        • 01-foo.zh.md
      • /09
        • 01-bar.en.md
        • 01-bar.zh.md

And links between the articles is necessary. Therefore, in order not to become a dead link when looking at GitHub with a Web browser, we set up a link as follows.

[link](/blog/2017/09/01-bar.en.md)

However, this has the problem of dead linking when displayed using Gatsby. Because the URL in the actually generated browser is as follows.

/[gatsby-config.pathPrefix]/en/blog/2017/09/01-bar

So, when I run gatsby build or gatsby develop, I want to replace links between articles using regular-expressions, as preprocessing to analyze Markdown by gatsby-transformer-remark.

How can I do the above?


Added: Feb, 2

I also tried relative links.

[link](../09/01-bar)

But the URL is /[gatsby-config.pathPrefix]/en/blog/2017/06/09/01-bar, which is dead link. Because Gatsby makes HTML place to /[gatsby-config.pathPrefix]/en/blog/2017/06/09/01-bar/index.html.

So I added ../ once more. And it worked. However, this has some problems.

  • I can not navigate from Markdown in GitHub to another Markdown. Because the relative path is different.
  • In addition, it cannot navigate without adding language suffix (e.g. 01-bar.en.md), but when I add it, Gatsby cannot be recognized this time and 404 or raw Markdown are displayed.

回答1:


You can create a plugin for gatsby-transformer-remark

plugins/gatsby-remark-relative-linker/index.js:

const visit = require('unist-util-visit');
module.exports = ({ markdownAST }) => {
  visit(markdownAST, 'link', node => {
    if (
      node.url &&
      !node.url.startsWith('//') &&
      !node.url.startsWith('http') &&
      node.url.startsWith('/')
    ) {
      node.url = node.url.replace(/(.*)\.(\w{2}).md(#.*)?$/, (match, base, language, hash) => {
        return `/${language}${base}${hash}`
      })
    }
  });

  return markdownAST;
};

plugins/gatsby-remark-relative-linker/package.json:

{}

./gatsby-config.js:

{
...
plugins: [
  {
    resolve: 'gatsby-transformer-remark',
    options: {
      plugins: [
        ...
        'gatsby-remark-relative-linker',
      ],
    }
  }
},

Here I am removing the .md from the urls and prefixing the language. Keep your urls as in markdown starting with / like [text](/blog/2017/09/01-bar.en.md)



来源:https://stackoverflow.com/questions/48553146/how-to-change-markdown-link-relative-path-as-preprocessing-of-gatsby-transformer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!