compatfactory

raw JSON →
4.0.4 verified Fri May 01 auth: no javascript

compatfactory v4.0.4 is a TypeScript library that unifies the TypeScript Compiler API factory functions across all TypeScript versions (3.x, 4.x, 5.x) and makes them conform with the Node Factory API. It solves the problem of different method signatures and availability across TypeScript versions, especially after the removal of old factory functions in TS 5.0. The library provides a single `ensureNodeFactory` function that accepts a `NodeFactory` or a `typescript` module and returns a normalized `NodeFactory` compatible with the latest API. It is actively maintained with frequent updates to support new TypeScript versions (e.g., v5.6, v5.5, v5.3 in v4.0.0). Key differentiators: simple wrapper, tiny footprint, supports all TypeScript versions in one package. Requires Node >=18.20.0.

error Cannot find module 'compatfactory' or its corresponding type declarations.
cause ESM-only package imported via require() or missing type module in package.json
fix
Use import { ensureNodeFactory } from 'compatfactory' in an ESM context (package.json with "type": "module")
error TypeError: ensureNodeFactory is not a function
cause Using default import instead of named import
fix
Use named import: import { ensureNodeFactory } from 'compatfactory'
error ReferenceError: exports is not defined in ES module scope
cause Mixing require() with ESM package
fix
Convert to ESM imports or use dynamic import: await import('compatfactory')
breaking Node 16 and 17 support dropped
fix Upgrade Node to >=18.20.0
breaking Default export no longer works in v4
fix Use named import: import { ensureNodeFactory } from 'compatfactory'
deprecated Default export deprecated
fix Switch to named export ensureNodeFactory
gotcha ensureNodeFactory with older TypeScript versions may return a wrapped factory; performance can differ
fix Cache the factory if called frequently; avoid repeated calls in hot paths
npm install compatfactory
yarn add compatfactory
pnpm add compatfactory

Demonstrates using ensureNodeFactory to create a normalized NodeFactory, then creating an import declaration with a unified API.

import { ensureNodeFactory } from 'compatfactory';
import ts from 'typescript';

// Create a source file for demonstration
const sourceFile = ts.createSourceFile(
  'test.ts',
  'const x: number = 1',
  ts.ScriptTarget.Latest
);

// Get normalized NodeFactory
const factory = ensureNodeFactory(ts);

// Use unified factory API (works across TS versions)
const newImport = factory.createImportDeclaration(
  undefined,
  factory.createImportClause(
    false,
    undefined,
    factory.createNamedImports([
      factory.createImportSpecifier(
        false,
        undefined,
        factory.createIdentifier('foo')
      )
    ])
  ),
  factory.createStringLiteral('./foo')
);

console.log(ts.createPrinter().printNode(ts.EmitHint.Unspecified, newImport, sourceFile));
// Output: import { foo } from "./foo"