@synvert-hq/node-mutation v1.18.2
NodeMutation
NodeMutation provides a set of APIs to rewrite node source code.
Table of Contents
Installation
Install NodeMutation using npm:
npm install --save @synvert-hq/node-mutationOr yarn;
yarn add @synvert-hq/node-mutationUsage
- initialize the NodeMutation instance:
import { Node } from "typescript"
mutation = new NodeMutation<Node>(filePath: string, source: string, { adapter: "typescript" | "espree" | "gonzales-pe" })- call the rewrite apis:
// append the code to the current node.
mutation.append(node: Node, code: string)
// delete source code of the child ast node
mutation.delete(node: Node, selectors: string | string[], options: DeleteOptions)
// insert code to the ast node.
mutation.insert(node: Node, code: string, options: InsertOptions)
// prepend code to the ast node.
mutation.prepend(node: Node, code: string)
// remove source code of the ast node
mutation.remove(node: Node, options: RemoveOptions)
// replace child node of the ast node with new code
mutation.replace(node: Node, selectors: string | string[], options: ReplaceOptions)
// replace the ast node with new code
mutation.replaceWith(node: Node, code: string)
// indent the ast node.
mutation.indent(node: Node, options: IndentOptions)
// no operation
mutation.noop(node: Node)
// group actions
mutation.group(() => {
mutation.delete(node: Node, selectors: string | string[], options: DeleteOptions)
mutation.insert(node: Node, code: string, options: InsertOptions)
})
// wrap the ast node
mutation.wrap(node: Node, options: WrapOptions)- process actions and write the new source code to file:
mutation.process()Evaluated Value
NodeMutation supports to evaluate the value of the node, and use the evaluated value to rewrite the source code.
source = 'class Synvert {}'
node = espree.parse(source)
mutation.replace node, '{{id}}', with: 'Foobar'
source # class Foobar {}See more in TypescriptAdapter, SyntaxTreeAdapter, and GonzalesPeAdapter
Configuration
adapter
Different parsers, like typescript and espree, will generate different AST nodes, to make NodeMutation work for them all, we define an Adapter interface, if you implement the Adapter interface, you can set it as NodeMutation's adapter.
It provides 3 adapters:
TypescriptAdapterEspreeAdapterGonzalesPeAdapter
NodeMutation.configure({ adapter: new EspreeAdapter() }); // default is TypescriptAdapterstrategy
It provides 2 strategies to handle conflicts when processing actions:
Strategy.KEEP_RUNNING: keep running and ignore the conflict action.Strategy.THROW_ERROR: throw error when conflict action is found.
NodeMutation.configure({ strategy: Strategy.KEEP_RUNNING }); // default is Strategy.THROW_ERRORtabWidth
NodeMutation.configure({ tabWidth: 4 }); // default is 2Contributing Guide
Fork and clone the repo.
Run
npm installto install dependencies.Run
npm run testornpm run watch:testto run tests.Make some changes and make tests all passed.
Push the changes to the repo.