Magicast allows you to programmatically modify JavaScript and Typescript source codes with a simplified, elegant and familiar syntax built on top of the AST parsed by recast and babel.
Roadmap:
🚧 Magicast is currently in the proof of concept state. While underlying parsers are stable, you might need to directly modify underlying AST for unsupported operations in the meantime.
Install npm package:
# using yarn
yarn add --dev magicast
# using npm
npm install -D magicast
# using pnpm
pnpm add -D magicast
Import utilities:
// ESM / Bundler
import { parseCode, generateCode, builders, createNode } from "magicast";
// CommonJS
const { parseCode, generateCode, builders, createNode } = require("magicast");
Example: Modify a file:
config.js
:
export default {
foo: ["a"],
};
Code to modify and append b
to foo
prop of defaultExport:
import { loadFile, writeFile } from "magicast";
const mod = await loadFile("config.js");
mod.exports.default.foo.push("b");
await writeFile(_module);
Updated config.js
:
export default {
foo: ["a", "b"],
};
Example: Directly use AST utils:
import { parseCode, generateCode } from "magicast";
// Parse to AST
const mod = parseCode(`export default { }`);
// Ensure foo is an array
mod.exports.default.foo ||= [];
// Add a new array member
mod.exports.default.foo.push("b");
mod.exports.default.foo.unshift("a");
// Generate code
const { code, map } = generateCode(mod);
Generated code:
export default {
foo: ["a", "b"],
};
Example: Get the AST directly:
import { parseCode, generateCode } from "magicast";
const mod = parseCode(`export default { }`);
const ast = mod.exports.default.$ast
// do something with ast
Example: Function parameters:
import { parseCode, generateCode } from "magicast";
const mod = parseCode(`export default defineConfig({ foo: 'bar' })`);
// Support for both bare object export and `defineConfig` wrapper
const options = mod.exports.default.$type === 'function-call'
? mod.exports.default.$args[0]
: mod.exports.default;
console.log(options.foo) // bar
- Clone this repository
- Install latest LTS version of Node.js
- Enable Corepack using
corepack enable
- Install dependencies using
pnpm install
- Run interactive tests using
pnpm dev
Made with 💛
Published under MIT License.