npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

magicast

v0.3.5

Published

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

Downloads

13,181,234

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.