Calyhre / gatsby-remark-abbr

Add abbr syntax support to gatsby-remark
1 stars 2 forks source link

Figured it out 😂 #4

Closed thesnups closed 4 years ago

thesnups commented 5 years ago

I, too, wanted to use remark-abbr in my Gatsby project and spent several hours struggling with this issue. We shouldn't need to duplicate the transformer function from remark-abbr in the gatsby-remark-abbr plugin. In the end, I came up with a solution that works:

const remarkAbbr = require('remark-abbr')

let transformer

function pluginWrapper(options) {
  transformer = remarkAbbr.call(this, options)
}

module.exports = function({ markdownAST }) {
  transformer(markdownAST)
}

module.exports.setParserPlugins = () => [[pluginWrapper, { expandFirst: true }]]

The only reason this workaround is necessary is because of how remark-abbr is implemented and exported. It works fine as a normal remark plugin, but gatsby-tranformer-remark seems to require the parser+compiler overrides function to live separately from the AST transformer function. Using the setParserPlugins export causes the plugin to run in the context of the Parser and Compiler in order to apply overrides/customizations, but the returned transformer function is ignored. It isn't applied to each markdown AST, so we still have to do that in the default export, as seen above.

Further, we cannot simply run remarkAbbr again in the default exported function because it crashes on the lines that attempt to access the Parser and Compiler. To address this, my workaround wraps the plugin in order to store a reference to the transformer function when the plugin is first run (as a result of returning it from setParserPlugins). We then apply the stored transformer function to each AST, resulting in the expected behavior.

Ideally, this issue gets fixed upstream in remark-abbr so that we don't need an ugly workaround such as this.

It's been a fun few hours 😛

Calyhre commented 4 years ago

Thanks for the awesome tip 👍 I implemented this solution and released under v2.0.0, now also allowing options to be passed to remark-abbr