Coder Social home page Coder Social logo

equivalent-exchange's Introduction

equivalent-exchange

Transmute one JavaScript string into another by way of mutating its AST. Powered by babel and recast.

Features

  • Can parse code using modern ES20XX syntax, as well as either TypeScript or Flow syntax.
  • Maintains the source formatting of the original source, where possible; only modified parts of the code will be touched.
  • Can generate a source map that maps your input file into your transformed output.

Usage Example

import { transmute, traverse, types } from "equivalent-exchange";

const someJs = "console.log('hi!');";

const result = transmute(someJs, (ast) => {
  traverse(ast, {
    StringLiteral(path) {
      const { node } = path;
      if (node.value === "hi!") {
        path.replaceWith(types.stringLiteral("goodbye!"));
      }
    },
  });
});

console.log(result.code); // console.log("goodbye!");

Note that you don't have to use the provided traverse or types; you can mutate the ast using whatever traversal method you prefer.

API Documentation

Please see api/index.d.ts for API documentation. There are lots of comments.

License

MIT

equivalent-exchange's People

Contributors

suchipi avatar adambrgmn avatar

Stargazers

Eva1ent avatar Caleb Williams avatar Kenny Goff avatar th37rose avatar Harvey avatar Saif Khayoon avatar Egor Lynov avatar Bell avatar Nathan Hutchision avatar Andrejs Agejevs avatar ebigram avatar Jaden Geller avatar Michael Chiche avatar Chris Rybicki avatar Taylor Everding avatar  avatar Sam Hindess avatar Ryan Sonshine avatar 爱可可-爱生活 avatar Marcis Bergmanis avatar Tyler Davis Mitchell avatar Jayphen avatar Ilya Radchenko avatar Chadwick Maycumber avatar  avatar Béré Cyriac avatar  avatar Victor Glindås avatar Taylor Hodge avatar Nick Beattie avatar blissful avatar John Johnson avatar asyrawi avatar Sebastian Higuita Castañeda avatar Cem Turan avatar RiN avatar Jarred Sumner avatar Viliam Kopecký avatar Patrick Smith avatar Aly Ahmed avatar Chris Witko avatar Nikolas Evers avatar Syntax avatar Guillaume Humbert avatar Munawwar avatar Juan P. Prieto avatar vidy avatar Fernando Rojo avatar PatrickJS avatar Daniel Del Core avatar Marshall Bowers avatar Talysson de Oliveira Cassiano avatar Nikita Popov avatar

Watchers

James Cloos avatar  avatar  avatar

Forkers

adambrgmn

equivalent-exchange's Issues

Issues with parsing jsx

This was exactly the kind of tool I was looking for, thanks for that! 👏
But I stumbled upon something that I really can't figure out. I have issues parsing code with JSX syntax.

Here's the way I did to reproduce:

  1. Create new project (npm init -y) and install equivalent-exchange (npm install equivalent-exchange)
  2. Create a file with the following content:
import { transmute, traverse } from 'equivalent-exchange';

const code = `
  export const Foo: React.FC<{ foo: string }> = ({foo}) => {
    return <div>{foo}</div>
  }
`;

try {
  transmute(code, { fileName: 'Foo.tsx' });
} catch (error) {
  console.error(error);
}
  1. Execute the script with node node script.mjs

With this I get the following error thrown:

Error: Line 3: Invalid regular expression: missing /
    at ErrorHandler.constructError (/project/node_modules/esprima/dist/esprima.js:5012:22)
    at ErrorHandler.createError (/project/node_modules/esprima/dist/esprima.js:5028:27)
    at ErrorHandler.throwError (/project/node_modules/esprima/dist/esprima.js:5035:21)
    at Scanner.throwUnexpectedToken (/project/node_modules/esprima/dist/esprima.js:5164:35)
    at Scanner.scanRegExpBody (/project/node_modules/esprima/dist/esprima.js:6139:23)
    at Scanner.scanRegExp (/project/node_modules/esprima/dist/esprima.js:6204:29)
    at Tokenizer.getNextToken (/project/node_modules/esprima/dist/esprima.js:6675:56)
    at Object.tokenize (/project/node_modules/esprima/dist/esprima.js:154:36)
    at Object.parse (/project/node_modules/recast/lib/parser.js:40:30)
    at codeToAst (/project/node_modules/equivalent-exchange/dist/index.js:45:24) {
  index: 90,
  lineNumber: 3,
  description: 'Invalid regular expression: missing /'
}

The strange thing is that when I clone this repo and try adding a test like this it all passes 🤔

test('with jsx syntax', async () => {
  const code = `export const Component: React.FC = () => {
    console.log("hello!");
    return <div />
  }`;

  const transform = (ast: AST) => {
    traverse(ast, {
      StringLiteral(path) {
        const { node } = path;
        if (node.value === 'hello!') {
          path.replaceWith(types.stringLiteral('goodbye!'));
        }
      },
    });
  };

  expect(() => {
    transmute(code, transform);
  }).not.toThrow();
});

Do you have any ideas of what might be going wrong? At first I thought of different babel versions colliding. But since it didn't work in my very bare-bones repro either I'm suspecting it is something else.

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.