pngwn / MDsveX

A markdown preprocessor for Svelte.
https://mdsvex.pngwn.io
MIT License
2.36k stars 102 forks source link

Allow users to pass a custom front-matter function #40

Closed pngwn closed 4 years ago

pngwn commented 4 years ago

mdsvex supports YAML front-matter out of the box but people might want to use a custom language in their fontmatter. As long as the function returns an object of key vaue pairs this should be fine.

Error handling needs to be considered as well, unified provides a really nice way to handle errors via messages on the vFile object, so some way to hook into this and provide custom error message/ object would be nice. See #39.

colinbate commented 4 years ago

Yes, I generally prefer TOML, so it would be nice to see some way to support that.

pngwn commented 4 years ago

This is implemented in the beta version, so will be supported in the next version which will be released shortly.

You can pass a series of options to customise frontmatter language. A parse function (which needs to return an object of key-value pairs or can return undefined for nothing/ fail), a type which is just a string naming it (I'm not actually sure if this is necessary and might remove it), and a marker which should be a string (you. might prefer +++ with TOML over --- so would pass +).

For parse errors, you can return undefined to carry on regardless and oush an error message to the messages array that is supplied as an argument. These messages will be printed to the console after parsing the document. You could also throw an error, if you wanted to.


import toml from 'toml';

const parse_toml = (fm, messages) => {
  try {
    return toml.parse(fm);
  } catch ({ line, column, message }) {
    messages.push(`Parsing error on line ${line}, column ${column} : ${message}`);
  }
};

mdsvex({
  frontmatter: {
    parse: parse_toml,
    type: 'toml',
    marker: '+',
});
pngwn commented 4 years ago

Done in 0.8