1
votes

I'm using Gatsby, and using the gatsby-transformer-remark plugin to load data into my page using graphQL. And I want to perform a custom string manipulations on some data stored in my Markdown frontmatter.

I thought using a custom YAML type would be a good way to do this because this can be done at compile time, and there's no need to do it at runtime. (The plugin run at compile time to generate data, I believe?) For example, I could define a custom type called max which returns the maximum number in a given array, and use it directly in the markdown file as follows:

---
foo: !max
  - 2
  - 4
  - 5
---

Is it possible to define a custom YAML type for the frontmatter parsed by gatsby-transformer-remark? Or, is there a different and better way to handle this situation?

I can see that the gatsby plugin uses grey-matter for parsing the front matter, which uses js-yaml for parsing YAML. I know it's possible to define custom YAML type in js-yaml. But, I can't seem to find how to pass options to js-yaml.

1

1 Answers

3
votes

If you'd like to pass options to js-yaml, you'd have to define a custom yaml engine, then pass it to gray-matter via gatsby-transformer-remark's options.

Define a custom yaml engine:

const yaml = require('js-yaml');
const schema = require('./custom-schema');

const customYamlEngine = (str) => yaml.safeLoad(str, { schema });
module.exports = customYamlEngine

And then pass it into gatsby-transformer-remark

const yaml = require('./custom-yaml');

module.exports = {
  plugins: [
    {
      resolve: `gatsby-transformer-remark`,
      options: {
+       engines: { yaml },
        plugins: [
          ...
        ],
      },
    },
  ]
}