Is there a way to use variable as URL in a MDX markdown link tag?

172 Views Asked by At

I am trying to use variables to manage links inside my documentation. I have declared an object that contains all my links like that:

export const Links = {
  "foo": "bar",
  "bar": "https://external.goo.com"
}

And I try to use those variables as link uri in a markdown link tag [Description]({Links.foo})

The issue is that MDX seems to not interpret the variable inside the () so the rendered content has this result :

export const Links = {
  "foo": "bar",
  "bar": "https://external.goo.com"
}

[the url should be bar, but is literal {foo}]({foo})

I managed to use variables using <a href={Links.foo}>this render variables correctly</a> but this is longer and less user friendly than using the []() syntax.

Is there a way to make this work (or maybe to override something in the MDX redering?) ?

Please, bear in mind that I am not a Javascript developper, so don't assume extended knowledge on that part from me :)

1

There are 1 best solutions below

0
On BEST ANSWER

As an alternative I used markdown reference style links.

As I am using docusaurus I use the docusaurus markdown pre-processor to inject a file that contains all markdown references.

This gives something like this

in foo.mdx

Checkout [my cool site][cool-site]

in _global_file_links.mdx

[cool-site]: https://my-cool-site.io "My cool site"

With the preprocessor I inject the _global_file_links.mdx at the end of each markdown file, all used reference gets rendered and the one not used are discarded.

Here is the preprocessor config in docusaurus.config.js:

const config = {
  // ...
  markdown: {
    format: "mdx",
    preprocessor: ({ filePath, fileContent }) => {
      console.log("Injecting global markdown references into " + filePath);
      const fs = require("node:fs");
      const links = fs.readFileSync("./docs/_global_file_links.mdx");
      return fileContent + "\n" + links;
    },
  },
  // ...
}

This is a dirty fix that works, but I think at this stage It should be a docusaurus plugin. (But I'm not a JS dev, so -_o_-)