unifiedjs / unified

☔️ interface for parsing, inspecting, transforming, and serializing content through syntax trees
https://unifiedjs.com
MIT License
4.49k stars 110 forks source link

this.use() doesn't respect plugin order when combined with unified().use() #190

Closed siefkenj closed 2 years ago

siefkenj commented 2 years ago

Calling unified with

unified().use(function() {
    this.use(plugin1)
}).use(plugin2)

seems to execute the plugins in the order pluign2 then plugin1. Is this the intended behavior? In my case, both plugins are transformer plugins.

wooorm commented 2 years ago

Yeah, this is intentional. First the plugins are added to a list, and not called yet. Only when they are needed, they are called, at which point your anonymous plugin adds plugin1 also to the list.

siefkenj commented 2 years ago

I see. So what is the proper way for a plugin to push many transformers onto the stack?

ChristianMurphy commented 2 years ago

It sounds like you want to make a preset? If so https://github.com/wooorm/remark-preset-wooorm gives an example of how that can look

wooorm commented 2 years ago
function myPlugin()
  return function manyTransforms(tree, file) {
    transformOne(tree, file)
    transformTwo(tree, file)
  }
}
siefkenj commented 2 years ago

To use your example above, transformOne is the actual transform function and not the plugin, right? So to do with plugins, I would do

function myPlugin(){
   return (tree, file) => {
      plugin1()(tree, file)
      plugin2()(tree, file)
   }
}

?

And if the transform returned a new tree instead of mutating the existing tree, I assume that would need to be manually accounted for?

wooorm commented 2 years ago

If you have multiple transforms, do what I did, not what you do. If you have multiple plugins, use a preset as Christian points out, not what you do.

If transforms return things, you have to handle that.

This all seems like an XY problem. You are asking about a solution and not about your problem. Perhaps you can formulate your question in more words.