diff --git a/packages/babel-helper-hoist-variables/package.json b/packages/babel-helper-hoist-variables/package.json index 590da1c08b92..ab0f2758f30b 100644 --- a/packages/babel-helper-hoist-variables/package.json +++ b/packages/babel-helper-hoist-variables/package.json @@ -13,7 +13,9 @@ "access": "public" }, "main": "lib/index.js", + "TODO": "The @babel/traverse dependency is only needed for the NodePath TS type. After converting @babel/core to TS we can import NodePath from there.", "dependencies": { + "@babel/traverse": "workspace:^7.12.17", "@babel/types": "workspace:^7.12.13" } } diff --git a/packages/babel-helper-hoist-variables/src/index.js b/packages/babel-helper-hoist-variables/src/index.ts similarity index 57% rename from packages/babel-helper-hoist-variables/src/index.js rename to packages/babel-helper-hoist-variables/src/index.ts index f69cac4f6e2e..c920b188ae31 100644 --- a/packages/babel-helper-hoist-variables/src/index.js +++ b/packages/babel-helper-hoist-variables/src/index.ts @@ -1,20 +1,36 @@ import * as t from "@babel/types"; +import type { NodePath } from "@babel/traverse"; + +export type EmitFunction = ( + id: t.Identifier, + idName: string, + hasInit: boolean, +) => any; + +type State = { + kind: "var" | "let"; + emit: EmitFunction; +}; + +type Unpacked = T extends (infer U)[] ? U : T; const visitor = { - Scope(path, state) { + Scope(path: NodePath, state: State) { if (state.kind === "let") path.skip(); }, - Function(path) { + Function(path: NodePath) { path.skip(); }, - VariableDeclaration(path, state) { + VariableDeclaration(path: NodePath, state: State) { if (state.kind && path.node.kind !== state.kind) return; const nodes = []; - const declarations: Array = path.get("declarations"); + const declarations: ReadonlyArray< + NodePath> + > = path.get("declarations"); let firstId; for (const declar of declarations) { @@ -42,6 +58,10 @@ const visitor = { }, }; -export default function (path, emit: Function, kind: "var" | "let" = "var") { +export default function hoistVariables( + path: NodePath, + emit: EmitFunction, + kind: "var" | "let" = "var", +) { path.traverse(visitor, { kind, emit }); } diff --git a/yarn.lock b/yarn.lock index df8b8b9ab390..04958e1a4608 100644 --- a/yarn.lock +++ b/yarn.lock @@ -537,6 +537,7 @@ __metadata: version: 0.0.0-use.local resolution: "@babel/helper-hoist-variables@workspace:packages/babel-helper-hoist-variables" dependencies: + "@babel/traverse": "workspace:^7.12.17" "@babel/types": "workspace:^7.12.13" languageName: unknown linkType: soft