diff --git a/packages/babel-traverse/src/path/removal.ts b/packages/babel-traverse/src/path/removal.ts index 3f74394ac6ef..21542724b9d8 100644 --- a/packages/babel-traverse/src/path/removal.ts +++ b/packages/babel-traverse/src/path/removal.ts @@ -30,8 +30,10 @@ export function _removeFromScope(this: NodePath) { } export function _callRemovalHooks(this: NodePath) { - for (const fn of hooks) { - if (fn(this, this.parentPath)) return true; + if (this.parentPath) { + for (const fn of hooks) { + if (fn(this, this.parentPath)) return true; + } } } diff --git a/packages/babel-traverse/test/removal.js b/packages/babel-traverse/test/removal.js index bf5adf398b56..eff722ae6ce0 100644 --- a/packages/babel-traverse/test/removal.js +++ b/packages/babel-traverse/test/removal.js @@ -152,4 +152,17 @@ describe("removal", function () { expect(rootPath.scope.hasBinding("x")).toBe(true); }); + + it("should not throw when removing without `Program`", function () { + const ast = parse("['1']").program.body[0].expression; + + traverse(ast, { + noScope: true, + StringLiteral(path) { + path.remove(); + }, + }); + + expect(ast.elements.length).toBe(0); + }); });