Knitwork JavaScript Code Generation Utilities

1.3.0 · active · verified Sun Apr 19

Knitwork is a utility library designed for programmatic generation of JavaScript and TypeScript code. It provides functions to construct various language constructs, including ESM `import` and `export` statements, dynamic imports, and TypeScript-specific elements like type imports, interfaces, and module augmentations. The library also offers robust serialization utilities for converting JavaScript objects and arrays into string representations, with options for raw or escaped values, and string escaping functions. Currently at stable version 1.3.0, Knitwork is actively maintained within the unjs ecosystem, receiving regular updates with a focus on modern JavaScript practices (ESM-first) and TypeScript integration. Its key differentiator lies in offering granular control over code generation for tasks like bundler plugins, build-time optimizations, and code transformation, providing a lower-level API compared to full AST manipulation libraries.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates generating various JavaScript and TypeScript code snippets, including imports, object serialization, interfaces, and exports using Knitwork's core utilities.

import { genImport, genObjectFromValues, genInterface, genExport, genString } from 'knitwork';

// Generate ESM imports
const importStatement = genImport('my-package', ['foo', { name: 'default', as: 'MyDefault' }]);
// ~> import { foo, default as MyDefault } from "my-package";

// Generate an object with escaped values
const dataObject = genObjectFromValues({
  name: 'Knitwork Demo',
  version: 1.0,
  isActive: true,
  config: {
    url: 'https://example.com/api',
    timeout: 5000
  }
});
// ~> { name: "Knitwork Demo", version: 1, isActive: true, config: { url: "https://example.com/api", timeout: 5000 } }

// Generate a TypeScript interface
const myInterface = genInterface('MyOptions', `{
  id: string;
  value: number;
}`);
// ~> interface MyOptions {
//      id: string;
//      value: number;
//    }

// Generate an export statement
const exportStatement = genExport('./types', { name: '*', as: 'MyTypes' });
// ~> export * as MyTypes from "./types";

console.log(importStatement + '\n\n' + dataObject + '\n\n' + myInterface + '\n\n' + exportStatement);

view raw JSON →