Files
babel/packages/babel-plugin-transform-async-to-generator/src/index.ts
magic-akari 910ece5e2a Optimize transform-async-to-generator output (#14122)
* Optimize `transform-async-to-generator` output

- remove wrapper if the function length is zero.
- remove wrapper if the `assumptions.ignoreFunctionLength` is `true`.

* chore: update test case and code style

* chore: add test
2022-01-08 21:01:20 +01:00

56 lines
1.4 KiB
TypeScript

import { declare } from "@babel/helper-plugin-utils";
import remapAsyncToGenerator from "@babel/helper-remap-async-to-generator";
import { addNamed } from "@babel/helper-module-imports";
import { types as t } from "@babel/core";
export default declare((api, options) => {
api.assertVersion(7);
const { method, module } = options;
const noNewArrows = api.assumption("noNewArrows");
const ignoreFunctionLength = api.assumption("ignoreFunctionLength");
if (method && module) {
return {
name: "transform-async-to-generator",
visitor: {
Function(path, state) {
if (!path.node.async || path.node.generator) return;
let wrapAsync = state.methodWrapper;
if (wrapAsync) {
wrapAsync = t.cloneNode(wrapAsync);
} else {
wrapAsync = state.methodWrapper = addNamed(path, method, module);
}
remapAsyncToGenerator(
path,
{ wrapAsync },
noNewArrows,
ignoreFunctionLength,
);
},
},
};
}
return {
name: "transform-async-to-generator",
visitor: {
Function(path, state) {
if (!path.node.async || path.node.generator) return;
remapAsyncToGenerator(
path,
{ wrapAsync: state.addHelper("asyncToGenerator") },
noNewArrows,
ignoreFunctionLength,
);
},
},
};
});