Skip to content

Latest commit

 

History

History
107 lines (73 loc) · 2.7 KB

README.md

File metadata and controls

107 lines (73 loc) · 2.7 KB

🧀 Magicast

npm version npm downloads Github Actions Codecov

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.

Usage

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("panner");

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 _module = await loadFile("config.js");

_module.exports.default.props.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 _module = parseCode(`export default { foo: ['a'] }`);

// Add a new array member
_module.exports.default.props.foo.push("b");

// Generate code
const { code, map } = generateCode(_module);

Development

  • 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

License

Made with 💛

Published under MIT License.