What is @babel/plugin-transform-async-to-generator?
The @babel/plugin-transform-async-to-generator package is a Babel plugin that transforms async functions into generator functions using the regenerator runtime, which is a part of the Facebook Regenerator project. This transformation allows async functions to be used in environments that do not natively support async/await syntax by converting them into ES2015/ES6 compatible code.
What are @babel/plugin-transform-async-to-generator's main functionalities?
Transform async functions to generators
This feature allows developers to write asynchronous code using the modern async/await syntax and have it transformed into generator functions that are compatible with older JavaScript engines.
async function foo() {
await bar();
}
// Transforms to:
function foo() {
return regeneratorRuntime.async(function foo$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return regeneratorRuntime.awrap(bar());
case 2:
case "end":
return _context.stop();
}
}
}, null, this);
}
Other packages similar to @babel/plugin-transform-async-to-generator
babel-plugin-transform-async-to-module-method
This package is similar to @babel/plugin-transform-async-to-generator in that it transforms async functions, but it does so by delegating to a specified module method, allowing for custom handling of async functions.
fast-async
Fast-async is a Babel plugin that uses nodent to transform async/await functions. It is designed to be faster than the regenerator-based approach used by @babel/plugin-transform-async-to-generator and does not require a runtime.
babel-preset-env
While not a direct alternative, babel-preset-env includes the capability to transform async functions when the target environments specified do not support them natively. It uses @babel/plugin-transform-async-to-generator as part of its transformation suite when necessary.
@babel/plugin-transform-async-to-generator
Turn async functions into ES2015 generators
In Babel 7, transform-async-to-module-method
was merged into this plugin
Example
In
async function foo() {
await bar();
}
Out
var _asyncToGenerator = function (fn) {
...
};
var foo = _asyncToGenerator(function* () {
yield bar();
});
Out with options
Turn async functions into a Bluebird coroutine
var Bluebird = require("bluebird");
var foo = Bluebird.coroutine(function* () {
yield bar();
});
Installation
npm install --save-dev @babel/plugin-transform-async-to-generator
Usage
Via .babelrc
(Recommended)
.babelrc
Without options:
{
"plugins": ["@babel/plugin-transform-async-to-generator"]
}
With options:
{
"plugins": [
["@babel/plugin-transform-async-to-generator", {
"module": "bluebird",
"method": "coroutine"
}]
]
}
Via CLI
babel --plugins @babel/plugin-transform-async-to-generator script.js
Via Node API
require("@babel/core").transform("code", {
plugins: ["@babel/plugin-transform-async-to-generator"]
});
References