CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nx--js

The JS plugin for Nx contains executors and generators that provide the best experience for developing JavaScript and TypeScript projects.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

typescript-utilities.mddocs/

TypeScript Utilities

@nx/js provides comprehensive TypeScript toolchain utilities including compilation, type checking, configuration management, AST manipulation, and transformer loading capabilities.

Capabilities

Type Checking

High-performance TypeScript type checking with incremental compilation support and detailed error reporting.

/**
 * Performs TypeScript type checking with configurable output modes
 * @param options - Type checking configuration options
 * @returns Promise resolving to type checking results with errors and file counts
 */
function runTypeCheck(options: TypeCheckOptions): Promise<TypeCheckResult>;

/**
 * Runs type checking in watch mode with continuous monitoring
 * @param options - Type checking configuration options
 * @param callback - Callback function for handling type check results
 * @returns Watch program with close method for cleanup
 */
function runTypeCheckWatch(
  options: TypeCheckOptions,
  callback: Function
): { close(): void };

/**
 * Formats TypeScript diagnostics for human-readable output
 * @param ts - TypeScript compiler API instance
 * @param workspaceRoot - Workspace root directory path
 * @param diagnostic - TypeScript diagnostic to format
 * @returns Formatted diagnostic string with file path and message
 */
function getFormattedDiagnostic(
  ts: typeof import('typescript'),
  workspaceRoot: string,
  diagnostic: Diagnostic
): string;

interface TypeCheckOptions {
  mode?: 'noEmit' | 'emitDeclarationOnly';  // Type checking mode
  tsConfigPath: string;                      // Path to TypeScript configuration
  workspaceRoot: string;                     // Workspace root directory
  incremental?: boolean;                     // Enable incremental type checking
  cacheDir?: string;                         // Cache directory for incremental builds
}

interface TypeCheckResult {
  warnings: string[];                        // Warning messages array
  errors: string[];                          // Error messages array
  inputFilesCount: number;                   // Number of input files processed
  totalFilesCount: number;                   // Total files in compilation
  incremental: boolean;                      // Whether incremental mode was used
}

interface BaseTypeCheckOptions {
  workspaceRoot: string;                     // Workspace root directory path
  tsConfigPath: string;                      // TypeScript configuration file path
}

interface NoEmitMode extends BaseTypeCheckOptions {
  mode: 'noEmit';                           // No output emission mode
}

interface EmitDeclarationOnlyMode extends BaseTypeCheckOptions {
  mode: 'emitDeclarationOnly';              // Emit only declaration files
  outDir: string;                           // Output directory for declarations
}

Usage Examples:

import { runTypeCheck, runTypeCheckWatch } from "@nx/js";

// Basic type checking
const result = await runTypeCheck({
  mode: 'noEmit',
  tsConfigPath: 'tsconfig.json',
  workspaceRoot: process.cwd(),
  incremental: true
});

if (result.errors.length > 0) {
  console.error('Type errors found:', result.errors);
}

// Watch mode type checking
const watcher = runTypeCheckWatch({
  mode: 'noEmit',
  tsConfigPath: 'tsconfig.json',
  workspaceRoot: process.cwd()
}, (result) => {
  console.log(`Checked ${result.inputFilesCount} files`);
});

// Clean up watcher
process.on('SIGINT', () => watcher.close());

TypeScript Configuration

Comprehensive TypeScript configuration reading, parsing, and path management utilities.

/**
 * Reads and parses a TypeScript configuration file
 * @param tsConfigPath - Path to tsconfig.json file
 * @param sys - Optional TypeScript system interface
 * @returns Parsed TypeScript command line configuration
 */
function readTsConfig(tsConfigPath: string, sys?: ts.System): ts.ParsedCommandLine;

/**
 * Reads TypeScript configuration from Nx Tree virtual file system
 * @param tree - Nx Tree instance
 * @param tsConfigPath - Path to tsconfig.json file
 * @returns Parsed TypeScript command line configuration
 */
function readTsConfigFromTree(tree: Tree, tsConfigPath: string): ts.ParsedCommandLine;

/**
 * Gets the root TypeScript configuration file path within Tree
 * @param tree - Nx Tree instance
 * @returns Root tsconfig path or null if not found
 */
function getRootTsConfigPathInTree(tree: Tree): string | null;

/**
 * Gets relative path from target to root TypeScript configuration
 * @param tree - Nx Tree instance
 * @param targetPath - Target directory path
 * @returns Relative path to root tsconfig
 */
function getRelativePathToRootTsConfig(tree: Tree, targetPath: string): string;

/**
 * Gets the root TypeScript configuration file path
 * @returns Root tsconfig path or null if not found
 */
function getRootTsConfigPath(): string | null;

/**
 * Gets the root TypeScript configuration filename
 * @param tree - Optional Nx Tree instance
 * @returns Root tsconfig filename or null if not found
 */
function getRootTsConfigFileName(tree?: Tree): string | null;

/**
 * Adds path mapping to TypeScript configuration
 * @param tree - Nx Tree instance
 * @param importPath - Import path to add
 * @param lookupPaths - Array of lookup paths for the import
 */
function addTsConfigPath(tree: Tree, importPath: string, lookupPaths: string[]): void;

/**
 * Reads path mappings from TypeScript configuration
 * @param tsConfig - TypeScript config path or parsed config
 * @returns Paths object or null if no paths found
 */
function readTsConfigPaths(tsConfig?: string | ts.ParsedCommandLine): Record<string, string[]> | null;

Usage Examples:

import { readTsConfig, addTsConfigPath, readTsConfigPaths } from "@nx/js";

// Read TypeScript configuration
const config = readTsConfig('tsconfig.json');
console.log('Compiler options:', config.options);

// Add path mapping
addTsConfigPath(tree, '@myorg/utils', ['libs/utils/src/index.ts']);

// Read existing path mappings
const paths = readTsConfigPaths('tsconfig.json');
console.log('Path mappings:', paths);

TypeScript Configuration Creation

Utilities for creating and extracting base TypeScript configurations.

/**
 * Default TypeScript compiler options for Nx projects
 */
const tsConfigBaseOptions: ts.CompilerOptions;

/**
 * Extracts base TypeScript configuration from workspace
 * @param host - Nx Tree instance
 * @returns Base TypeScript configuration object
 */
function extractTsConfigBase(host: Tree): { compilerOptions: ts.CompilerOptions };

Usage Example:

import { tsConfigBaseOptions, extractTsConfigBase } from "@nx/js";

// Use default options
const defaultOptions = tsConfigBaseOptions;

// Extract from existing configuration
const baseConfig = extractTsConfigBase(tree);

AST Manipulation

Powerful TypeScript AST manipulation utilities for code transformations and modifications.

/**
 * Resolves module path by import statement
 * @param importExpr - Import expression string
 * @param filePath - File path containing the import
 * @param tsConfigPath - TypeScript configuration file path
 * @returns Resolved module path or undefined if not found
 */
function resolveModuleByImport(
  importExpr: string,
  filePath: string,
  tsConfigPath: string
): string | undefined;

/**
 * Inserts code at specified position in source file
 * @param host - Nx Tree instance
 * @param sourceFile - TypeScript source file
 * @param filePath - File path for the source file
 * @param insertPosition - Position to insert at
 * @param contentToInsert - Content to insert
 * @returns Updated TypeScript source file
 */
function insertChange(
  host: Tree,
  sourceFile: ts.SourceFile,
  filePath: string,
  insertPosition: number,
  contentToInsert: string
): ts.SourceFile;

/**
 * Replaces content at specified position in source file
 * @param host - Nx Tree instance
 * @param sourceFile - TypeScript source file
 * @param filePath - File path for the source file
 * @param insertPosition - Position to replace at
 * @param contentToInsert - New content to insert
 * @param oldContent - Old content to replace
 * @returns Updated TypeScript source file
 */
function replaceChange(
  host: Tree,
  sourceFile: ts.SourceFile,
  filePath: string,
  insertPosition: number,
  contentToInsert: string,
  oldContent: string
): ts.SourceFile;

/**
 * Removes content at specified position in source file
 * @param host - Nx Tree instance
 * @param sourceFile - TypeScript source file
 * @param filePath - File path for the source file
 * @param removePosition - Position to remove at
 * @param contentToRemove - Content to remove
 * @returns Updated TypeScript source file
 */
function removeChange(
  host: Tree,
  sourceFile: ts.SourceFile,
  filePath: string,
  removePosition: number,
  contentToRemove: string
): ts.SourceFile;

/**
 * Inserts import statement into source file
 * @param host - Nx Tree instance
 * @param source - TypeScript source file
 * @param fileToEdit - File path to edit
 * @param symbolName - Symbol name to import
 * @param fileName - Module file name to import from
 * @param isDefault - Whether this is a default import
 * @returns Updated TypeScript source file
 */
function insertImport(
  host: Tree,
  source: ts.SourceFile,
  fileToEdit: string,
  symbolName: string,
  fileName: string,
  isDefault?: boolean
): ts.SourceFile;

/**
 * Adds global statement to source file
 * @param host - Nx Tree instance
 * @param source - TypeScript source file
 * @param modulePath - Module path for the source file
 * @param statement - Statement to add
 * @returns Updated TypeScript source file
 */
function addGlobal(
  host: Tree,
  source: ts.SourceFile,
  modulePath: string,
  statement: string
): ts.SourceFile;

/**
 * Gets import information from source file based on predicate
 * @param source - TypeScript source file
 * @param predicate - Predicate function for filtering imports
 * @returns Array of import information objects
 */
function getImport(source: ts.SourceFile, predicate: (a: any) => boolean): any[];

/**
 * Replaces node value in source file
 * @param host - Nx Tree instance
 * @param sourceFile - TypeScript source file
 * @param modulePath - Module path for the source file
 * @param node - AST node to replace
 * @param content - New content for the node
 * @returns Updated TypeScript source file
 */
function replaceNodeValue(
  host: Tree,
  sourceFile: ts.SourceFile,
  modulePath: string,
  node: ts.Node,
  content: string
): ts.SourceFile;

/**
 * Adds parameter to class constructor
 * @param tree - Nx Tree instance
 * @param source - TypeScript source file
 * @param modulePath - Module path for the source file
 * @param opts - Options with className and param details
 * @returns Updated TypeScript source file
 */
function addParameterToConstructor(
  tree: Tree,
  source: ts.SourceFile,
  modulePath: string,
  opts: { className: string; param: string }
): ts.SourceFile;

/**
 * Adds method to class
 * @param tree - Nx Tree instance
 * @param source - TypeScript source file
 * @param modulePath - Module path for the source file
 * @param opts - Options with className, methodHeader, and optional body
 * @returns Updated TypeScript source file
 */
function addMethod(
  tree: Tree,
  source: ts.SourceFile,
  modulePath: string,
  opts: { className: string; methodHeader: string; body?: string }
): ts.SourceFile;

/**
 * Finds class declaration in source file
 * @param source - TypeScript source file
 * @param className - Class name to find
 * @param silent - Whether to suppress errors if not found
 * @returns Class declaration node
 */
function findClass(source: ts.SourceFile, className: string, silent?: boolean): ts.ClassDeclaration;

/**
 * Finds nodes of specific syntax kinds in AST
 * @param node - Root AST node to search from
 * @param kind - Syntax kind or array of kinds to search for
 * @param max - Maximum number of nodes to return
 * @returns Array of matching AST nodes
 */
function findNodes(node: ts.Node, kind: ts.SyntaxKind | ts.SyntaxKind[], max?: number): ts.Node[];

Usage Examples:

import { insertImport, findClass, addMethod, resolveModuleByImport } from "@nx/js";
import * as ts from 'typescript';

// Resolve module import
const resolvedPath = resolveModuleByImport(
  './utils',
  'src/main.ts',
  'tsconfig.json'
);

// Add import to file
const sourceFile = ts.createSourceFile('test.ts', sourceCode, ts.ScriptTarget.Latest);
const updatedFile = insertImport(
  tree,
  sourceFile,
  'src/test.ts',
  'helper',
  './utils',
  false
);

// Find and modify class
const classNode = findClass(sourceFile, 'MyClass');
const withMethod = addMethod(tree, sourceFile, 'src/test.ts', {
  className: 'MyClass',
  methodHeader: 'public doSomething(): void',
  body: 'console.log("Hello World");'
});

Source Node Utilities

Utilities for extracting and working with TypeScript AST nodes.

/**
 * Gets all AST nodes from a TypeScript source file
 * @param sourceFile - TypeScript source file
 * @returns Array of all AST nodes in the source file
 */
function getSourceNodes(sourceFile: ts.SourceFile): ts.Node[];

Usage Example:

import { getSourceNodes } from "@nx/js";
import * as ts from 'typescript';

const sourceFile = ts.createSourceFile('test.ts', sourceCode, ts.ScriptTarget.Latest);
const allNodes = getSourceNodes(sourceFile);
console.log(`Found ${allNodes.length} AST nodes`);

Transformer Loading

Advanced TypeScript transformer plugin loading and configuration system.

/**
 * Loads TypeScript transformer plugins with configuration
 * @param plugins - Array of transformer entries (names or configurations)
 * @param moduleResolver - Optional module resolution function
 * @returns Object with compiler plugin hooks and plugin detection flag
 */
function loadTsTransformers(
  plugins: TransformerEntry[],
  moduleResolver?: typeof require.resolve
): { compilerPluginHooks: CompilerPluginHooks; hasPlugin: boolean; };

interface TransformerPlugin {
  name: string;                         // Transformer plugin name
  options: Record<string, unknown>;     // Plugin configuration options
}

type TransformerEntry = string | TransformerPlugin;

interface CompilerPlugin {
  before?(program: ts.Program, options?: any): ts.TransformerFactory<ts.SourceFile>;
  after?(program: ts.Program, options?: any): ts.TransformerFactory<ts.SourceFile>;
  afterDeclarations?(program: ts.Program, options?: any): ts.TransformerFactory<ts.SourceFile>;
}

interface CompilerPluginHooks {
  before: Array<(program: ts.Program) => ts.TransformerFactory<ts.SourceFile>>;
  after: Array<(program: ts.Program) => ts.TransformerFactory<ts.SourceFile>>;
  afterDeclarations: Array<(program: ts.Program) => ts.TransformerFactory<ts.SourceFile>>;
}

Usage Example:

import { loadTsTransformers } from "@nx/js";

const transformers = loadTsTransformers([
  'typescript-transform-paths',
  {
    name: 'custom-transformer',
    options: { customOption: true }
  }
]);

if (transformers.hasPlugin) {
  // Use transformers in TypeScript compilation
  const program = ts.createProgram(fileNames, options);
  const beforeTransformers = transformers.compilerPluginHooks.before.map(t => t(program));
}

Dependency Management

Utilities for adding TypeScript-related dependencies to projects.

/**
 * Adds tslib dependencies to package.json
 * @param tree - Nx Tree instance
 */
function addTsLibDependencies(tree: Tree): void;

Usage Example:

import { addTsLibDependencies } from "@nx/js";

// Add tslib dependencies to the project
addTsLibDependencies(tree);

Diagnostic Printing

Utilities for formatting and printing TypeScript diagnostics.

/**
 * Prints TypeScript diagnostics with formatting
 * @param errors - Array of error messages
 * @param warnings - Array of warning messages
 * @returns Promise that resolves when printing is complete
 */
function printDiagnostics(errors?: string[], warnings?: string[]): Promise<void>;

Usage Example:

import { printDiagnostics } from "@nx/js";

const errors = ['Type error: Cannot assign string to number'];
const warnings = ['Warning: Unused variable'];

await printDiagnostics(errors, warnings);

Install with Tessl CLI

npx tessl i tessl/npm-nx--js

docs

additional-utilities.md

asset-management.md

executors.md

generators.md

index.md

package-management.md

typescript-utilities.md

tile.json