Search code examples
node.jsbabeljsvisitor-patternbabel-plugin

What's the difference between "Visitor.Program.enter()" and "pre()" in a Babel plugin?


This Babel plugin:

module.exports = function(){
    return {
        visitor:{   
            Program:{
                enter(){ console.log('Enter') },
                exit(){ console.log('Exit') }
            }
        },
        pre(){ console.log('Pre') },
        post(){ console.log('Post') }
    }
}

produces this output for any javascript file:

Pre
Enter
Exit
Post

pre()is called right before Program.enter() and post() right after Program.exit().

If I want to run some code at the beginning/end of the AST traversal, is there any reason I should put that code inside pre/post instead of Program.enter/Program.exit?

Does it make any difference?


Solution

  • There's no difference AFAIK. Both are called before/after the syntax tree has been completely traversed.

    The only difference would be that the parameters pass to Program.enter/Program.exit are different from the parameters passed to pre/post.

    module.exports = function(){
        return {
            visitor:{   
                Program:{
                    enter(path, state){
                        //path.node
                        //path.parent
                        //state.opts
                    },
                }
            },
            pre(state){
                //state.scope
                //state.scope.globals
                //state.scope.plugins
            },
        }
    }
    

    For example, from Program.enter() you have access to state.opts with your plugin options, whereas from pre() you don't.