this.hub is undefined in Babel traverse
See original GitHub issueBug Report
This related to #8617
- I would like to work on a fix!
Current Behavior
@babel/parser
has a different behavior when estree
enabled, and when not.
Input Code
When estree
disabled code with Duplicated variable declaration
throws while parsing:
const {parse} = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const code = `function square(n) {
const n = 1;
}`;
// crash with an error: Identifier 'n' has already been declared (1:16)
const ast = parse(code);
When estree
mode enabled code is parsed, but can’t be traversed because of this.hub
is undefined:
const {parse} = require('@babel/parser');
const traverse = require('@babel/traverse').default;
const code = `function square(n) {
const n = 1;
}`;
const ast = parse(code, {
plugins: [
'estree',
]
});
traverse(ast, {
enter(path) {
console.log('n');
}
});
/*
throw this.hub.buildError(id, `Duplicate declaration "${name}"`, TypeError);
^
TypeError: Cannot read property 'buildError' of undefined
at Scope.checkBlockScopedCollisions (/home/coderaiser/node_modules/@babel/traverse/lib/scope/index.js:402:22)
*/
Same result when instead of estree
plugin, errorRecovery
enabled.
Expected behavior/code
Would be great if in estree
mode babel
throws while parsing and/or can throw while traversing
about Duplicate declaration
.
Environment
- Babel version(s):
v7.9.4
- Node/npm version: Node 12(13)/npm 6
- OS:
Ubuntu
- Monorepo: no
- How you are using Babel:
parse
,traverse
Possible Solution
I suggest to use TypeError
, because this is what hub actually does, this way:
throw TypeError(`Duplicate declaration "${name}"`);
If of course buildError
doesn’t used in development purpose to set breakpoint on error building, anyways Chrome Developer Tools
debugger already suggest similar feature pause on exceptions
(caught and uncaught).
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (2 by maintainers)
Top GitHub Comments
@rob-myers Please don’t rely on the internal file structures on
@babel/core
, they could change. Instead you can importFile
from the wildcardbabel
You can wrap the parsed ast into a
File
class (defined in@babel/core
) sothis.hub
is available, like we did in #10575.I admit that this workaround is not ideal as ultimately
babel/traverse
should be allowed to run as a standalone package. Historically there has been attempt on fixing this issue (#5050) but later reverted in #5306.@coderaiser I think we can surely revisit this issue and see if we can re-land #5050. PR is welcome.