CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-swc--cli

This package provides a command-line interface for the SWC (Speedy Web Compiler) project, a super-fast TypeScript/JavaScript compiler and bundler written in Rust.

Pending
Overview
Eval results
Files

swc-cli.mddocs/

SWC CLI

Core compilation functionality for transforming TypeScript and JavaScript files with extensive configuration options, watch mode, and parallel processing.

Capabilities

Main CLI Command

The primary SWC compilation command with comprehensive options for file transformation.

npx swc [options] <files...>

# Key Options:
-d, --out-dir [out]           # Compile to output directory
-o, --out-file [out]          # Compile to single output file  
-w, --watch                   # Watch for file changes
-s, --source-maps [type]      # Generate source maps (true|false|inline|both)
-q, --quiet                   # Suppress compilation output
--sync                        # Use synchronous compilation
--workers [number]            # Number of parallel workers
-C, --config <config>         # Override config from .swcrc
--config-file [path]          # Path to .swcrc file
--extensions [list]           # File extensions to compile
--ignore [list]               # Glob patterns to ignore
--only [list]                 # Glob patterns to include only
--copy-files                  # Copy non-compilable files
--include-dotfiles            # Include dotfiles in compilation
--strip-leading-paths         # Remove leading directory paths
--delete-dir-on-start         # Clean output directory before compilation
--out-file-extension [ext]    # Use specific output file extension

Usage Examples:

# Basic compilation
npx swc src/index.ts -o lib/index.js

# Directory compilation with source maps
npx swc src -d lib --source-maps

# Watch mode with workers
npx swc src -d lib --watch --workers 4

# Custom extensions and ignore patterns
npx swc src -d lib --extensions .ts,.tsx --ignore "**/*.test.ts"

# Override config
npx swc src -d lib -C module.type=commonjs -C jsc.target=es2018

Programmatic API

Direct programmatic access to directory compilation functionality.

/**
 * Compile a directory of files using SWC
 * @param options - Configuration object containing CLI and SWC options
 * @returns Promise that resolves when compilation completes
 */
function swcDir(options: {
  cliOptions: CliOptions;
  swcOptions: Options;
  callbacks?: Callbacks;
}): Promise<void>;

interface CliOptions {
  /** Output directory path */
  readonly outDir: string;
  /** Output file path for single file compilation */
  readonly outFile: string;
  /** Remove leading directory paths in output */
  readonly stripLeadingPaths: boolean;
  /** Use synchronous compilation (useful for debugging) */
  readonly sync: boolean;
  /** Number of parallel workers (undefined for default) */
  readonly workers: number | undefined;
  /** Source map target file name */
  readonly sourceMapTarget?: string;
  /** Input filename for stdin compilation */
  readonly filename: string;
  /** Array of input file patterns */
  readonly filenames: string[];
  /** File extensions to compile */
  readonly extensions: string[];
  /** Enable watch mode */
  readonly watch: boolean;
  /** Copy non-compilable files to output */
  readonly copyFiles: boolean;
  /** Custom output file extension */
  readonly outFileExtension?: string;
  /** Include dotfiles in compilation */
  readonly includeDotfiles: boolean;
  /** Delete output directory before compilation */
  readonly deleteDirOnStart: boolean;
  /** Suppress compilation output */
  readonly quiet: boolean;
  /** Glob patterns to include only */
  readonly only: string[];
  /** Glob patterns to ignore */
  readonly ignore: string[];
}

interface Callbacks {
  /** Called on successful compilation */
  readonly onSuccess?: (data: {
    duration: number;
    compiled?: number;
    copied?: number;
    filename?: string;
  }) => any;
  /** Called on compilation failure */
  readonly onFail?: (data: {
    duration: number;
    reasons: Map<string, string>;
  }) => any;
  /** Called when watch mode is ready */
  readonly onWatchReady?: () => any;
}

Usage Example:

import { swcDir } from "@swc/cli";

await swcDir({
  cliOptions: {
    outDir: "lib",
    outFile: "",
    stripLeadingPaths: false,
    sync: false,
    workers: undefined,
    filename: "",
    filenames: ["src"],
    extensions: [".ts", ".tsx", ".js", ".jsx"],
    watch: false,
    copyFiles: true,
    includeDotfiles: false,
    deleteDirOnStart: true,
    quiet: false,
    only: [],
    ignore: ["**/*.test.ts"],
  },
  swcOptions: {
    jsc: {
      target: "es2018",
      parser: {
        syntax: "typescript",
      },
    },
    module: {
      type: "commonjs",
    },
    sourceMaps: true,
  },
  callbacks: {
    onSuccess: ({ duration, compiled, copied }) => {
      console.log(`Compiled ${compiled} files in ${duration}ms`);
    },
    onFail: ({ duration, reasons }) => {
      console.error(`Compilation failed after ${duration}ms`);
      for (const [file, reason] of reasons) {
        console.error(`${file}: ${reason}`);
      }
    },
  },
});

Options Parsing

Parse command-line arguments into structured options.

/**
 * Initialize the CLI program with all available options
 */
function initProgram(): void;

/**
 * Parse command-line arguments into CLI and SWC options
 * @param args - Command-line arguments array
 * @returns Parsed options or undefined on error
 */
function parseArgs(args: string[]): {
  swcOptions: Options;
  cliOptions: CliOptions;
} | undefined;

/** Default file extensions supported by SWC */
const DEFAULT_EXTENSIONS: string[] = [
  ".js", ".jsx", ".es6", ".es", ".mjs", 
  ".ts", ".tsx", ".cts", ".mts"
];

Utility Functions

Helper functions for file operations and compilation tasks.

/**
 * Check if a file or directory exists
 * @param path - Path to check
 * @returns Promise resolving to existence boolean
 */
function exists(path: string): Promise<boolean>;

/**
 * Transform source code using SWC
 * @param filename - Source filename
 * @param code - Source code string
 * @param opts - SWC transformation options
 * @param sync - Use synchronous transformation
 * @param outputPath - Optional output path
 * @returns Promise resolving to transformation result
 */
function transform(
  filename: string,
  code: string,
  opts: Options,
  sync: boolean,
  outputPath: string | undefined
): Promise<Output>;

/**
 * Compile a file using SWC
 * @param filename - Input filename
 * @param opts - SWC compilation options
 * @param sync - Use synchronous compilation
 * @param outputPath - Optional output path
 * @returns Promise resolving to compilation result or void if ignored
 */
function compile(
  filename: string,
  opts: Options,
  sync: boolean,
  outputPath: string | undefined
): Promise<Output | void>;

/**
 * Write compiled output to file with optional source maps
 * @param output - SWC compilation output
 * @param filename - Output filename
 * @param sourceMaps - Source map configuration
 */
function outputFile(
  output: Output,
  filename: string,
  sourceMaps: undefined | Options["sourceMaps"]
): void;

/**
 * Get destination path for compiled file
 * @param filename - Source filename
 * @param outDir - Output directory
 * @param stripLeadingPaths - Remove leading paths
 * @param ext - Optional file extension override
 * @returns Destination file path
 */
function getDest(
  filename: string,
  outDir: string,
  stripLeadingPaths: boolean,
  ext?: string
): string;

/**
 * Map TypeScript extensions to JavaScript extensions
 * @param filename - Input filename
 * @returns JavaScript file extension
 */
function mapTsExt(filename: string): string;

File Discovery

Functions for finding and filtering source files.

/**
 * Find all input files based on source globs
 * @param sources - Array of source patterns
 * @param only - Glob patterns to include only
 * @param ignore - Glob patterns to ignore
 * @param includeDotfiles - Include dotfiles in results
 * @returns Promise resolving to array of matching files
 */
function globSources(
  sources: string[],
  only: string[],
  ignore: string[],
  includeDotfiles?: boolean
): Promise<string[]>;

/**
 * Test if filename has a compilable extension
 * @param filename - Filename to test
 * @param allowedExtension - Array of allowed extensions
 * @returns True if filename is compilable
 */
function isCompilableExtension(
  filename: string,
  allowedExtension: string[]
): boolean;

/**
 * Split file list into compilable and copyable files
 * @param files - Array of file paths
 * @param allowedExtension - Array of compilable extensions
 * @param copyFiles - Whether to include copyable files
 * @returns Tuple of [compilable files, copyable files]
 */
function splitCompilableAndCopyable(
  files: string[],
  allowedExtension: string[],
  copyFiles: boolean
): [compilable: string[], copyable: string[]];

/**
 * Set up file watching for source files
 * @param sources - Array of source patterns to watch
 * @param includeDotfiles - Include dotfiles in watching
 * @param only - Glob patterns to include only
 * @param ignore - Glob patterns to ignore
 * @returns Promise resolving to chokidar watcher instance
 */
function watchSources(
  sources: string[],
  includeDotfiles?: boolean,
  only?: string[],
  ignore?: string[]
): Promise<import("chokidar").FSWatcher>;

Types

enum CompileStatus {
  Copied,
  Compiled,
  Omitted,
  Failed,
}

// Re-exported from @swc/core
type Options = import("@swc/core").Options;
type Output = import("@swc/core").Output;

Install with Tessl CLI

npx tessl i tessl/npm-swc--cli

docs

index.md

spack.md

swc-cli.md

swcx.md

tile.json