export = : TypeScript's CommonJS Export Syntax
Think of `export =` as TypeScript's version of `module.exports`. It replaces a module's entire export with a single value, like a class or function. It's used for compatibility with CommonJS modules. The footgun is mixing it with standard `export`s.
WHY IT EXISTS Before ES Modules became the standard, Node.js used the CommonJS module system, which revolved around a global require function and a module.exports object. TypeScript needed a way to author modules that could cleanly export a single, primary value (like a class or a function) to be consumed by CommonJS-style require() calls. export = was created for this specific purpose.
THE MENTAL MODEL Think of export = as a direct assignment to module.exports. While standard export statements add properties to the exports object, export = completely replaces the object with whatever you assign. This means a module using export = can only have one single thing it exports.
HOW IT WORKS In a TypeScript file, you designate a single entity as the module's export. For example: class MyClass { /* ... */ } export = MyClass;. To import this module, you must use a specific TypeScript syntax: import MyClass = require('./my-module');. This import = require() syntax is the counterpart to export =. The compiler translates this pair into the appropriate CommonJS module.exports and require() calls.
WHEN TO USE IT Use export = when you need to produce a CommonJS module, which is common in Node.js environments or when your tsconfig.json has "module": "commonjs". It's particularly useful for creating declaration files (.d.ts) for existing JavaScript libraries that use the module.exports = ... pattern. It provides the most accurate type representation for that style of module.
WHEN NOT TO USE IT Avoid export = in any modern, new TypeScript project targeting ES Modules ("module": "esnext" or similar). The standard export default and named export syntax is more flexible, compatible with modern bundlers and runtimes, and is the official JavaScript standard. export = is not compatible with ES Module-only targets.
ONE CANONICAL EXAMPLE A common footgun is mixing export = with other top-level exports. TypeScript will throw an error: "A module cannot have multiple default exports." You must commit to one style per file. If you use export = MyClass;, you cannot also have export const myVar = 42; in the same file. The export = must be the only export statement.
Read the original → typescriptlang.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.