Coder Social home page Coder Social logo

lorsque-sir / magicast Goto Github PK

View Code? Open in Web Editor NEW

This project forked from unjs/magicast

0.0 0.0 0.0 478 KB

๐Ÿง€ Programmatically modify JavaScript and TypeScript source codes with a simplified, elegant and familiar syntax powered by recast and babel.

License: MIT License

TypeScript 100.00%

magicast's Introduction

๐Ÿง€ 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);

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 parameters:

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 (e) {
    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.

magicast's People

Contributors

antfu avatar pi0 avatar renovate[bot] avatar lms24 avatar tahul avatar mannil avatar larbish avatar hugoattal avatar igorbabko avatar liuseen-l avatar andarist avatar samuelstroschein avatar atinux avatar betteroneday avatar zoeyzhao19 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.