https://github.com/devongovett/to-ast
Converts JavaScript objects to equivalent ASTs
https://github.com/devongovett/to-ast
Last synced: over 1 year ago
JSON representation
Converts JavaScript objects to equivalent ASTs
- Host: GitHub
- URL: https://github.com/devongovett/to-ast
- Owner: devongovett
- Created: 2015-04-02T03:48:06.000Z (about 11 years ago)
- Default Branch: master
- Last Pushed: 2019-08-12T04:20:31.000Z (almost 7 years ago)
- Last Synced: 2025-02-27T05:51:13.152Z (over 1 year ago)
- Language: JavaScript
- Size: 117 KB
- Stars: 34
- Watchers: 4
- Forks: 5
- Open Issues: 3
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
# to-ast
This module converts JavaScript objects to an equivalent abstract syntax tree representation,
compatible with the [Mozilla Parser API](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Parser_API).
You can use it to generate JavaScript source code from objects, using
[escodegen](https://github.com/estools/escodegen).
## Usage
Install with npm:
npm install to-ast
Here's a simple example:
```javascript
var toAST = require('to-ast');
var escodegen = require('escodegen');
// get an AST from a number...
toAST(2) //=> { type: 'Literal', value: 2 }
// or if you want a source string...
escodegen.generate(toAST(2)) //=> '2'
```
## Supported types
* undefined
* null
* number, string, and boolean literals
* functions
* Node buffers
* arrays
* String, Number, and Boolean object wrappers
* typed arrays and array buffers
* dates
* errors
* regular expressions
* object literals
## Custom types
Most built-in JavaScript types as supported out of the box, but if you want to override the behavior for
your particular object, you can provide a `toAST` method on your object:
```javascript
var toAST = require('to-ast');
var escodegen = require('escodegen');
function Person(name) {
this.name = name;
}
Person.prototype.toAST = function() {
return {
type: 'NewExpression',
callee: { type: 'Identifier', name: 'Person' },
arguments: [{ type: 'Literal', value: this.name }]
};
};
escodegen.generate(toAST(new Person('Devon'))) //=> "new Person('Devon')"
```
## License
MIT