Get current filename in Babel Plugin?
Asked Answered
F

3

28

I'm attempting to write a plugin for babel, and am needing the filename of the current file that is being parsed. I know the lines of the code are passed in, but I haven't managed to find a reference to the filename. Any help??

For instance given this code what could I do

export default function({ types: t }) {
  return {
    visitor: {
      Identifier(path) {
       // something here??
      }
    }
  };
}
Farmhouse answered 8/3, 2016 at 1:23 Comment(0)
E
54

You can you this or use the 2nd parameter in a visitor (state)

Identifier(path, state) {
    console.log(state.file.opts.filename);
}
Eiger answered 8/3, 2016 at 18:18 Comment(1)
Why not state.filename?Lianeliang
F
9

For any future viewers, you can use this.file.opts.filename in a visitor function

Farmhouse answered 8/3, 2016 at 6:58 Comment(0)
G
0

The property state.file.opts.filename will give the full path to the file being transformed. S.t. like: /Users/casianorodriguezleon/campus-virtual/2324/learning/babel-macros/src/tan-li/use-macro.mjs. The property state.file.sourceFileName gives the basename of the input file: use-macro.mjs

Geminian answered 20/6, 2024 at 12:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.