Is there a plan to support inserting declaration statements?
imguolao opened this issue · 1 comments
imguolao commented
Describe the feature
expect
Insert a new statement before (or after) a statement.
import { parseModule, generateCode } from "magicast";
// Parse to AST
const mod = parseModule(`export default { }`);
// Insert a declaration statement before the `export default` statement
mod.exports.before(`const a = "VariableDeclarator";`);
// Ensure foo is an array
mod.exports.default.foo ||= [];
// Add a variable as a new array member
mod.exports.default.foo.push("a", "var");
/**
* const a = "VariableDeclarator";
* export default {
* foo: [a],
* };
*/
console.log(generateCode(mod).code);
Additional information
- Would you be willing to help implement this feature?
antfu commented
Sounds reasonable. I think we could use $append
and $prepend
on every node? Prefix with $
indicates it's a special operation and avoids conflicts with the namespace.