Node reuse versus cloning #16314
-
I'm writing a small plugin and I was wondering: Is it okay to reuse nodes? For example, given input import { foo } from "path";
import { bar } from "path"; and output import { foo, bar } from "path"; Could I insert the specifier node for What about identifiers? Can they be reused without cloning? I checked the handbook (and past discussions) but I don't see any mention of cloning or node reuse :) |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 6 replies
-
Nodes can be moved but cannot be reused. |
Beta Was this translation helpful? Give feedback.
-
Thanks! I didn't notice the 2nd parameter of What does "moved" mean in this context? Is it okay as long as the original path is removed, or are there specific functions for moving nodes? |
Beta Was this translation helpful? Give feedback.
-
Thanks for the answers! |
Beta Was this translation helpful? Give feedback.
-
Oh, one more question (kind of unrelated). It seems that if I do the following, it also removes the associated binding: const scope = path1.scope; // path1.scope === path2.scope
console.log(Object.keys(scope.bindings));
path2.pushContainer('specifiers', specifier);
path1.get('specifiers')[index].remove();
console.log(Object.keys(scope.bindings)); shows the binding for the specifier being removed (regardless of whether I push first or remove first). Should I just splice the specifiers array instead? const scope = path1.scope; // path1.scope === path2.scope
console.log(Object.keys(scope.bindings));
path2.pushContainer('specifiers', specifier);
path1.node.specifiers.splice(index, 1);
console.log(Object.keys(scope.bindings)); shows the binding being preserved and I still see the import statement being adjusted, but I don't know if I'm messing up the state. |
Beta Was this translation helpful? Give feedback.
This is a long-standing problem with Babel, where current binding information is not always reliable.
In fact, the former should be recommended, but it may actually cause side effects. You can use it flexibly according to actual needs.
If you wish to use precise binding information, use
path.scope.crawl()
to refresh the binding information.