ranlexer
TypeScript icon, indicating that this package has built-in type declarations

0.0.9 • Public • Published

ranlexer

Tiny JavaScript parser and generator


Build Status npm-v npm-d brotli module formats: umd, esm

Install

Using npm:

npm install ranlexer --save

Usage

ranlexer can export the following methods

  • parse: Parse the code into an ast
  • walk: Walk through the structure of the ast to perform custom operations
  • generate: Parse the ast into code
  • build: A lightweight build tool that supports treeshaking

parse

Parse the code into an ast:

import { parse } from 'ranlexer'

const code = 'let a = 1;'
const ast = parse(code)

walk

Walk through the structure of the ast to perform custom operations

There are two options:

  • ast: ast structure node
  • opts: One object with two methods in it
// Export the type of the ast node
import type { Types } from 'ranlexer'

const opts = {
  enter: (node: Types.Node) => {
    // Enter the processing of the node
  },
  leave: (node: Types.Node) => {
    // Leave the node processing
  }
walk(ast, opts)

generate

Parse the ast into code:

import { generate } from 'ranlexer'

const ast = {
  type: NodeType.Program,
  start: 0,
  end: 9,
  body: [
    {
      type: NodeType.VariableDeclaration,
      start: 0,
      end: 9,
      declarations: [
        {
          type: NodeType.VariableDeclarator,
          id: {
            type: NodeType.Identifier,
            name: 'a',
            start: 4,
            end: 5,
          },
          start: 4,
          end: 9,
          init: {
            type: NodeType.Literal,
            value: '1',
            raw: '1',
            start: 8,
            end: 9,
          },
        },
      ],
      kind: 'let',
    },
  ],
}
const code = generate(ast) // 'let a = 1;'

build

A lightweight build tool that supports treeshaking

import { build } from 'ranlexer'

const bundle = await build(option)

Generate a bundle by passing in options,All options are well, optional:

  • input: Build entry, if not set, the default value is ./index.js
  • output: Path to the build output file. If not set, the default value is ./dist/index.js
  • external: String array,the modules in the array are not built

The bundle has two methods:

  • generate: generate is to output the built code directly,
import { build } from 'ranlexer'

const bundle = await build(option)

const code = bundle.generate()
  • write: write is to output the file to a directory.
import { build } from 'ranlexer'

const bundle = await build(option)

bundle.write()

Meta

LICENSE (MIT)

Package Sidebar

Install

npm i ranlexer

Weekly Downloads

11

Version

0.0.9

License

MIT

Unpacked Size

204 kB

Total Files

30

Last publish

Collaborators

  • chaxus