@putout/engine-parser

10.8.0 • Public • Published

@putout/engine-parser NPM version

🐊Putout engine that parses input.

Install

npm i @putout/engine-parser

Supported parsers

Any parser should be installed before use, but you can be sure that @babel/parse always installed.

API

By default @putout/printer used. It formats code according to eslint-plugin-putout rules but without using ESLint.

But you can also use recast or babel with:

const ast = parse(source, {
    printer: 'recast',
});

const code = print(ast, {
    printer: 'recast',
});

When you need to pass options, use:

const code = print(ast, {
    printer: ['putout', {
        format: {
            indent: '    ',
        },
    }],
});

print(ast [, options])

Print code from ast

parse(code, [, options])

You can add default options for custom parser you use.

template.fresh(code)

parse without memoization.

template.ast(code)

create node using memoization.

template.ast.fresh(code)

create node without memoization.

template.extractExpression(code)

Extract expression node from ExpressionStatement.

Sourcemaps

You have two ways to benefit from source map generation:

  • using Recast print;
  • using Babel generator;

Generate sourcemaps using Recast

const source = `const hello = 'world';`;

const ast = parse(source, {
    printer: 'recast',
    sourceFileName: 'hello.js',
});

print(ast, {
    printer: 'recast',
    sourceMapName: 'hello.map',
});

// returns
`const hello = 'world';
{"version":3,"sources":["hello.js"],"names":[],"mappings":"AAAA...","file":"hello.map","sourcesContent":["const hello = 'world';"]}`;

Generate sourcemaps using Babel

To generate sourcemap using babel generator, you should use babel parser before. This is low level transformation, because Babel doesn't preserve any formatting.

const {generate} = require('@putout/engine-parser');
const babel = require('@putout/engine-parser/babel');

const ast = babel.parse(source, {
    sourceFilename: 'hello.js',
});

generate(ast, {sourceMaps: true}, {
    'hello.js': source,
});

// returns
({
    code,
    map,
});

Example

const {parse} = require('@putout/engine-parser');
const parser = 'acorn';

const code = parse('var t = "hello"', {
    parser,
});

License

MIT

/@putout/engine-parser/

    Package Sidebar

    Install

    npm i @putout/engine-parser

    Weekly Downloads

    16,928

    Version

    10.8.0

    License

    MIT

    Unpacked Size

    18.5 kB

    Total Files

    19

    Last publish

    Collaborators

    • coderaiser