Helper function to hoist variable declarations in JavaScript AST transformations
npx @tessl/cli install tessl/npm-babel-helper-hoist-variables@6.24.0A Babel helper function that hoists variable declarations in JavaScript AST transformations. This utility traverses AST paths to find variable declarations and converts them into separate declaration and assignment statements, effectively hoisting the variable declarations to their containing scope while maintaining proper JavaScript semantics.
npm install babel-helper-hoist-variablesESM:
import hoistVariables from "babel-helper-hoist-variables";CommonJS:
const hoistVariables = require("babel-helper-hoist-variables");import hoistVariables from "babel-helper-hoist-variables";
import { parse } from "babel-parser";
import traverse from "babel-traverse";
// Parse some code
const ast = parse(`
function example() {
var a = 1, b = 2;
let c = 3;
}
`);
// Use in a Babel transformation
traverse(ast, {
FunctionDeclaration(path) {
const hoistedVars = [];
// Hoist 'var' declarations
hoistVariables(path, (identifier, name) => {
hoistedVars.push(identifier);
}, "var");
console.log("Hoisted variables:", hoistedVars);
}
});The main export hoists variable declarations from a given AST path by converting them into separate declaration and assignment statements.
/**
* Hoists variable declarations from an AST path
* @param {NodePath} path - The Babel AST path to traverse for variable hoisting (from babel-traverse)
* @param {Function} emit - Callback function that receives hoisted identifiers
* @param {("var"|"let")} kind - The kind of variable declarations to hoist (default: "var")
* @returns {undefined} - This function performs side effects and doesn't return a value
*/
function hoistVariables(path, emit, kind = "var");path (Required): The Babel AST NodePath object to traverse for variable hoisting (from babel-traverse)emit (Required): Callback function that receives each hoisted identifier
emit(identifier, name)identifier: Babel identifier node for the hoisted variablename: String name of the variablekind (Optional): String literal specifying which variable declaration types to hoist
"var" or "let""var"The function traverses the provided AST path using a visitor pattern that:
kind parameteremit callback)Collecting Hoisted Variables:
const hoistedVars = [];
hoistVariables(path, (identifier, name) => {
hoistedVars.push(identifier);
});Adding to Scope:
hoistVariables(path, (identifier, name) => {
scope.push({ id: identifier });
});Filtering by Declaration Kind:
// Only hoist 'let' declarations
hoistVariables(path, emitFunction, "let");// From babel-traverse
interface NodePath {
// Babel AST path with traversal and manipulation methods
}
// From babel-types
interface Identifier {
// Babel identifier AST node
}This package depends on:
When using this package, you'll typically also need: