Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

magicast

unjs10.2mMIT0.3.5TypeScript support: included

Modify a JS/TS file and write back magically just like JSON!

readme

🧀 Magicast

npm version npm downloads bundle Codecov License JSDocs

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.

❯ 🧙🏼 Magical modify a JS/TS file and write back magically just like JSON!
❯ 🔀 Exports/Import manipulate module's imports and exports at ease
❯ 💼 Function Arguments easily manipulate arguments passed to a function call, like defineConfig()
❯ 🎨 Smart Formatting preseves the formatting style (quotes, tabs, etc.) from the original code
❯ 🧑‍💻 Readable get rid of the complexity of AST manipulation and make your code super readable

Install

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 { parseModule, generateCode, builders, createNode } from "magicast";

// CommonJS
const { parseModule, generateCode, builders, createNode } = require("magicast");

Examples

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(mod, "config.js");

Updated config.js:

export default {
  foo: ["a", "b"],
};

Example: Directly use AST utils:

import { parseModule, generateCode } from "magicast";

// Parse to AST
const mod = parseModule(`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 { parseModule, generateCode } from "magicast";

const mod = parseModule(`export default { }`);

const ast = mod.exports.default.$ast;
// do something with ast

Example: Function arguments:

import { parseModule, generateCode } from "magicast";

const mod = parseModule(`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

Example: Create a function call:

import { parseModule, generateCode, builders } from "magicast";

const mod = parseModule(`export default {}`);

const options = (mod.exports.default.list = builders.functionCall(
  "create",
  [1, 2, 3],
));

console.log(mod.generateCode()); // export default { list: create([1, 2, 3]) }

Notes

As JavaScript is a very dynamic language, you should be aware that Magicast's convention CAN NOT cover all possible cases. Magicast serves as a simple and maintainable interface to update static-ish JavaScript code. When interacting with Magicast node, be aware that every option might have chance to throw an error depending on the input code. We recommend to always wrap the code in a try/catch block (even better to do some defensive coding), for example:

import { loadFile, writeFile } from "magicast";

function updateConfig() {
  try {
    const mod = await loadFile("config.js");

    mod.exports.default.foo.push("b");

    await writeFile(mod);
  } catch {
    console.error("Unable to update config.js");
    console.error(
      "Please update it manually with the following instructions: ...",
    );
    // handle error
  }
}

High Level Helpers

We also experiment to provide a few high level helpers to make common tasks easier. You could import them from magicast/helpers. They might be moved to a separate package in the future.

import {
  deepMergeObject,
  addNuxtModule,
  addVitePlugin,
  // ...
} from "magicast/helpers";

We recommend to check out the source code and test cases for more details.

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.

changelog

Changelog

v0.3.5

compare changes

🚀 Enhancements

  • Add $prepend and $append APIs to imports (#124)

📦 Build

  • Fix types exports (#123)

🏡 Chore

❤️ Contributors

v0.3.4

compare changes

🚀 Enhancements

  • Support logical and member expression (#111)

🏡 Chore

❤️ Contributors

v0.3.3

compare changes

🚀 Enhancements

  • Support ArrowFunctionExpression (#98)

🏡 Chore

  • Update deps and test snaps (122409f)

❤️ Contributors

v0.3.2

compare changes

🩹 Fixes

  • Quoted properties of ObjectExpression not in exports proxy (#94)

🏡 Chore

❤️ Contributors

v0.3.1

compare changes

🩹 Fixes

  • Unable to get value using NumericLiteral or BooleanLiteral type keys (#91)

🏡 Chore

❤️ Contributors

v0.3.0

compare changes

🩹 Fixes

  • ⚠️ writeFile now requires filename (#79)

📦 Build

  • Bundle recast (#81)

🏡 Chore

⚠️ Breaking Changes

  • ⚠️ writeFile now requires filename (#79)

❤️ Contributors

v0.2.11

compare changes

🚀 Enhancements

  • helpers: Handle Vite config declarations with satisfies keyword (#82)

🏡 Chore

🤖 CI

❤️ Contributors

v0.2.10

compare changes

🚀 Enhancements

  • helpers: Handle Vite config objects declared as variables in addVitePlugin (#69)

🩹 Fixes

  • object: Handle nested keys kebab-case style (#71)

🏡 Chore

❤️ Contributors

v0.2.9

compare changes

🚀 Enhancements

  • DeepMergeObject improvements; NumericLiteral and StringLiteral keys (#63)

🏡 Chore

❤️ Contributors

v0.2.8

compare changes

🩹 Fixes

  • Type resolution in node16 environments (#60)
  • helpers: Improve deepMergeObject handling case (#62)

🏡 Chore

❤️ Contributors

v0.2.7

compare changes

🩹 Fixes

  • createProxy: Trap for the 'in' operator (#58)

❤️ Contributors

  • Zoeyzhao19

v0.2.6

compare changes

🩹 Fixes

🏡 Chore

❤️ Contributors

v0.2.5

compare changes

🚀 Enhancements

  • Add Vite plugin at a given index (#53)

🩹 Fixes

  • Support code with as and satisfies (#55)

🏡 Chore

❤️ Contributors

v0.2.4

compare changes

🩹 Fixes

  • Enumerable keys for exports and imports, close #38 (#38)
  • Make proxied module enumerable, close #47 (#47)

📖 Documentation

🏡 Chore

✅ Tests

  • Add identifier as property example (fb77b5d)

❤️ Contributors

v0.2.3

compare changes

🩹 Fixes

  • Enumerable keys for exports and imports, close #38 (#38)

❤️ Contributors

v0.2.2

compare changes

🚀 Enhancements

  • Add identifier casting (#39)

❤️ Contributors

v0.2.1

compare changes

🚀 Enhancements

  • Support builder.raw (4983f47)
  • Support builder.newExpression (cf5ad6d)

📖 Documentation

❤️ Contributors

v0.2.0

compare changes

🚀 Enhancements

  • Support delete operation (ad40a7b)
  • Support more array operation (90040ee)
  • Use proxy for top level module (#8)
  • imports support (#11)
  • Support Date, Set, and Map to literalToAst (b97d8f2)
  • Automatically preserve code style (#10)
  • Improve error system (4a286e2)
  • Construct function call (#15)
  • Improve typescript support (9d9bd43)
  • Support mod.generate (b27e2b5)
  • ⚠️ parseModule and parseExpression (#24)
  • Add high level helpers (912c135)

🔥 Performance

🩹 Fixes

  • Improve edge cases of literalToAst (f9b6296)

💅 Refactors

  • ⚠️ Rename .arguments to .$args for functions (#7)
  • Use @babel/types over estree (308fd21)
  • Split test files (dcc759e)
  • Break down test files (5af3f8c)
  • Break down files (fecdee1)
  • ⚠️ Rename builder to builders (0dd8e9a)

📖 Documentation

🏡 Chore

⚠️ Breaking Changes

  • ⚠️ parseModule and parseExpression (#24)
  • ⚠️ Rename .arguments to .$args for functions (#7)
  • ⚠️ Rename builder to builders (0dd8e9a)

❤️ Contributors