compatfactory
raw JSON →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.
Common errors
error Cannot find module 'compatfactory' or its corresponding type declarations. ↓
error TypeError: ensureNodeFactory is not a function ↓
error ReferenceError: exports is not defined in ES module scope ↓
Warnings
breaking Node 16 and 17 support dropped ↓
breaking Default export no longer works in v4 ↓
deprecated Default export deprecated ↓
gotcha ensureNodeFactory with older TypeScript versions may return a wrapped factory; performance can differ ↓
Install
npm install compatfactory yarn add compatfactory pnpm add compatfactory Imports
- ensureNodeFactory wrong
const ensureNodeFactory = require('compatfactory')correctimport { ensureNodeFactory } from 'compatfactory' - NodeFactory (type)
import type { NodeFactory } from 'compatfactory' - default export (deprecated) wrong
import { default as compatfactory } from 'compatfactory'correctimport compatfactory from 'compatfactory'
Quickstart
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"