Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to run async code in a Babel Plugin Visitor?

I'm working on a babel plugin that runs some code through an async module. I need to wait on that result before I modify the path.

visitor: {
  TaggedTemplateExpression(path) {
    if (path.node.tag.name !== 'Style') return;

    ProcessStyle(path).then((data) => {
      path.replaceWith(t.StringLiteral(data.data));
    });
  },
}

Is this currently possible?

like image 650
Benjamin Solum Avatar asked Aug 31 '25 06:08

Benjamin Solum


2 Answers

Babel's API, for example babel.transform(), synchronously returns the resulting transformed. This means that plugins have no way of being async, because Babel itself is fully synchronous.

Depending on what your requirements are, you could consider using child_process.execSync to synchronously run another Node process to do your async work while blocking Babel.

like image 173
loganfsmyth Avatar answered Sep 03 '25 23:09

loganfsmyth


https://github.com/ForbesLindesay/sync-rpc

this runs async code in a separate process, and communicates over a network connection

i found it surprisingly hard to do this reliably with child_process and execSync / spawnSync. i always had problems with limited buffer size, even when setting maxBuffer to Infinity, resulting in incomplete data transfers and mysterious syntax errors (code lines were cut off after some 1000 characters)

like image 30
Mila Nautikus Avatar answered Sep 03 '25 23:09

Mila Nautikus