Search code examples
markdowngatsbyremarkjs

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


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.

Solution

  • 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)