npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

esgen

v0.2.11

Published

ECMAScript generator

Downloads

18

Readme

ECMAScript Generator

NPM Build Status Code Quality Coverage GitHub Project API Documentation

Supported features:

Choose what you need. If strings concatenation is just enough - that's definitely the way to go.

See API Documentation for the details.

Simple Usage

import { esGenerate } from 'esgen';

const text = await esGenerate(code => {
  code
    .write(`function print(text) {`)
    .indent(`console.log(text);`)
    .write('}')
    .write(`const greeting = 'Hello, World!';`)
    .write(`print(greeting);`);
});

The following code will be emitted:

function print(text) {
  console.log(text);
}
const greeting = 'Hello, World!';
print(greeting);

Symbols And Functions

Symbols used to avoid naming conflicts. If the same name requested for two different symbols, one of them will be automatically renamed.

The example above can utilize symbols:

import { EsFunction, EsVarSymbol, esGenerate, esStringLiteral, esline } from 'esgen';

// Create function.
const print = new EsFunction(
  'print',
  {
    text: {}, // Require argument called `text`.
  },
  {
    declare: {
      at: 'bundle', // Automatically declare function at top level once referred.
      body: fn => code => {
        code.write(
          // Place on one line.
          esline`console.log(${fn.args.text /* Refer declared argument symbol */});`,
        );
      },
    },
  },
);

const text = await esGenerate(code => {
  // Create variable symbol.
  const greeting = new EsVarSymbol('greeting');

  code
    .write(
      // Declare variable explicitly.
      greeting.declare({
        // Initialize it with string literal.
        value: () => esStringLiteral('Hello, World!'),
      }),
    )
    .write(
      // Call `print()` function.
      esline`${print.call({
        text: greeting /* Pass variable as argument. */,
      })};`,
    );
});

Symbol Exports And Code Evaluation

Symbols can be exported from the bundle. In this case it is possible to evaluate emitted code immediately and obtain the exported symbols.

For example, to export the function print() from the example above, the following can be done:

import { EsFunction, esEvaluate, esline } from 'esgen';

// Create function.
const printFn = new EsFunction(
  'print',
  {
    text: {}, // Require argument called `text`.
  },
  {
    declare: {
      at: 'exports', // Automatically export function once referred.
      body: fn => code => {
        code.write(
          // Place on one line.
          esline`console.log(${fn.args.text /* Refer declared argument symbol */});`,
        );
      },
    },
  },
);

// Evaluate emitted code.
const { print } = (await esEvaluate((_, { ns }) => {
  // Explicitly refer the function to force its emission.
  ns.refer(printFn);
})) as { print: (text: string) => void };

print('Hello, World!');

Classes

Classes represented by EsClass instances.

Class may have a base class, constructor, and members.

import { EsClass, EsField, EsMemberVisibility, EsMethod, esEvaluate, esline } from 'esgen';

// Declare class
//
// export class Printer { ... }
//
const printer = new EsClass('Printer', {
  classConstructor: {
    args: {
      // Optional argument key ends with `?`.
      'initialText?': {
        comment: 'Default text to print',
      },
    },
  },
  declare: {
    // Export class from the bundle.
    at: 'exports',
  },
});

// Declare private field (without initializer).
//
// #defaultText;
//
const defaultText = new EsField('defaultText', {
  visibility: EsMemberVisibility.Private,
}).declareIn(printer);

// Declare class constructor.
//
// constructor(initialText = 'Hello, World!') {
//   this.#defaultText = initialText;
// }
//
printer.declareConstructor({
  args: {
    initialText: {
      // Assign default value to optional argument.
      declare: naming => esline`${naming} = 'Hello, World!'`,
    },
  },
  body: ({
    member: {
      args: { initialText },
    },
  }) => esline`${defaultText.set('this', initialText)};`,
});

// Declare public method.
//
// print(text = this.#defaultText) {
//   console.log(test);
// }
//
new EsMethod('print', {
  args: { 'text?': { comment: 'Text to print' } },
}).declareIn(printer, {
  args: {
    text: {
      declare: naming => esline`${naming} = ${defaultText.get('this')}`,
    },
  },
  body: ({
    member: {
      args: { text },
    },
  }) => esline`console.log(${text});`,
});

// Evaluate emitted code.
const { Printer } = (await esEvaluate((_, { ns }) => {
  // Explicitly refer the class to force its emission.
  ns.refer(printer);
})) as {
  Printer: new (initialText?: string) => { print(text?: string): void };
};

const instance = new Printer();

instance.print(); // Hello, World!
instance.print('My text'); // My text.