unjs/magicast

Allow adding import statement after existing imports

bluwy opened this issue · 1 comments

Describe the feature

Currently imports added (with $add) prepends before any other import statements in the file. There's also a TODO to consider appending instead:

const declaration = imports.find(
(i) => i.from === value.from,
)?.$declaration;
if (declaration) {
// TODO: insert after the last import maybe?
declaration.specifiers.push(specifier as any);
} else {
root.body.unshift(
b.importDeclaration([specifier], b.stringLiteral(value.from)) as any,
);
}

It would be nice if we can add import statements after existing imports.


There's a comment at #45 (comment) that suggests adding $append and $prepend to all the nodes. Maybe we can apply the same idea for .imports only for now?


I'm trying to migrate Astro to use this, but I think this issue is the only blocker before it's ready: withastro/astro#11772. There's other new lines formatting difference, but I think it's not a big deal.

Additional information

  • Would you be willing to help implement this feature?

Yeah sure! $append and $prepend sounds good to me.