Sub topic 9
Fix imports and exports and module interop
This chapter covers what changes in import and export statements when a file moves from JavaScript to TypeScript. It assumes you have a working tsconfig.json from the setup chapter, know the difference between CommonJS (require) and ES modules (import), and have already renamed a file to .ts.
Why modules cause errors during conversion
JavaScript projects often mix module styles. A file may use require() and module.exports because it was written for older Node.js versions. Another may use import and export because a bundler handles it.
TypeScript reads module syntax to decide what a file exports and what an import is worth. Three things matter:
- Whether the file is a module. A
.tsfile with no top-levelimportorexportis a script, and its top-level declarations become global. - Which syntax you wrote. TypeScript understands
importandexportfully. A barerequire()call returnsanyin many setups. - What the
modulesetting intsconfig.jsontells the compiler to emit.
Convert require and module.exports
Here is a typical CommonJS file, src/format.js.
const path = require("path");
function formatPath(p) {
return path.basename(p).toUpperCase();
}
module.exports = { formatPath };After renaming it to format.ts, rewrite it with ES module syntax.
import path from "path";
export function formatPath(p: string): string {
return path.basename(p).toUpperCase();
}TypeScript compiles this to whatever module format your module option requests. With "module": "commonjs", the output uses require and exports, so Node.js runs it as before. You write ES module syntax and the compiler handles the output.
The consumer changes too. A JavaScript file that used const { formatPath } = require("./format") still works at runtime against the compiled output. A TypeScript consumer should write the following.
import { formatPath } from "./format";
console.log(formatPath("/tmp/report.txt"));Do not add .ts to the import path. Write ./format. With "module": "commonjs" this is correct. If you later switch to Node's native ES module mode ("module": "node16" or "nodenext"), relative imports must include the output extension, such as ./format.js, even though the source file is format.ts.
Default and named exports
module.exports = something and export default something are not the same thing in TypeScript, and this is the most common source of confusion.
| JavaScript (CommonJS) | TypeScript equivalent |
|---|---|
| `module.exports = fn` | `export default fn` (needs interop for CommonJS consumers) or `export = fn` |
| `module.exports = { a, b }` | `export { a, b }` or `export function a() {}` |
| `exports.a = a` | `export const a = a` style named export |
| `const x = require("x")` | `import x from "x"` or `import * as x from "x"` |
| `const { a } = require("x")` | `import { a } from "x"` |
Named exports are the safer default. They give editors reliable autocomplete and rename support, and they avoid the question of whether a consumer sees the default under .default.
If a file does module.exports = fn and you want to keep that exact runtime shape, TypeScript offers export = with a matching import x = require("x"). Use this only when other CommonJS code that you cannot change depends on the exact shape.
esModuleInterop
The starter tsconfig.json set "esModuleInterop": true. This option controls how default imports from CommonJS packages behave.
Many npm packages use module.exports = something. They have no real default export. Without interop, import express from "express" fails type checking, because the type declarations describe a module with no default. The compiler suggests writing import * as express from "express", and that version can fail at runtime when you call it.
With esModuleInterop enabled:
import x from "pkg"works for packages that usemodule.exports = ....- The compiler emits small helper functions (
__importDefaultand__importStar) that wrap CommonJS modules so that.defaultexists. import * as x from "pkg"produces a namespace object, which is not callable. Use it only when you want the members.
The next table shows what to write for a CommonJS package that exports a function or an object.
| Package shape | Import to use with esModuleInterop |
|---|---|
| Exports a function or class (`module.exports = fn`) | `import fn from "pkg"` |
| Exports an object with members | `import { member } from "pkg"` |
| Exports an object and you want all of it | `import * as pkg from "pkg"` |
Keep esModuleInterop on for the whole migration. Turning it off midway changes how imports are emitted and can break working code.
Module resolution and the module setting
Two options decide how TypeScript finds and emits modules.
modulesets the output format.commonjsemitsrequire.esnextores2020keepsimportin the output.node16andnodenextfollow Node's rules and decide per file based on the nearestpackage.json.moduleResolutionsets how an import string maps to a file. For a Node.js project, the defaults that come withmoduleare usually right.
The starter config uses commonjs, which matches existing require-based Node projects. Keep that during the migration. Changing the module system and the language in one step makes errors hard to attribute.
Mixed JavaScript and TypeScript files
With allowJs on, TypeScript files can import JavaScript files and the reverse. Some points to know:
- A TypeScript file that imports a
.jsfile receives types inferred from the JavaScript source. If the JavaScript usesmodule.exports, TypeScript recognizes common patterns and treats the file as a module. - A JavaScript file that has not been checked can export values whose inferred types are loose. Imports from it may be
anyin places. Annotating or converting the file removes the looseness. - A JavaScript file still using
requireto load a file you have converted works, because the output indistis plain CommonJS.
Common errors and fixes
These messages appear most often after converting module syntax.
Module '"x"' has no default export.The package has nodefault. EnableesModuleInteropor use a named import.Cannot find module './x' or its corresponding type declarations.The path is wrong, the file is not underrootDir, or it is a package with no types. Third-party packages are covered in the next chapter.Could not find a declaration file for module 'x'.The package ships JavaScript only. Install@types/xif it exists.'x' is declared but its value is never read.This appears only withnoUnusedLocals. It is not part of the starter config.Cannot redeclare block-scoped variable 'x'.Two scripts (files with no import or export) declare the same top-level name. Add anexport {}line to make the file a module.
// Turns this file into a module so its top-level names stay local.
export {};
const helper = 42;Type-only imports
When you import something that exists only as a type, such as an interface, you can mark it with import type.
import type { User } from "./user";
import { formatUser } from "./format";
const u: User = { name: "Ada", age: 36 };
console.log(formatUser(u));import type is erased completely from the output. It makes clear that no runtime dependency exists, and it avoids circular import problems at runtime. Compilers that transpile one file at a time, such as Babel or esbuild, need this form when isolatedModules is enabled, because they cannot see whether an import is a type.
A conversion checklist for imports
- Replace
requirewithimport, keeping the same module paths. - Replace
module.exportsandexports.xwithexport. - Prefer named exports. Keep a default export only when callers need it.
- Add
export {}to any file that has no imports or exports. - Use
import typefor interfaces and type aliases. - Compile with
npx tsc --noEmitand fix import errors first, because they hide other errors.
Exercise
A file contains const express = require("express"); and module.exports = { start };. Rewrite both lines in TypeScript module syntax. Which tsconfig.json option makes the express import work as a default import, and why?
Show answer
Use import express from "express"; and export { start }; (or export function start() {}). The option is esModuleInterop: true. Express uses module.exports = ... and has no real default export, so the option makes the compiler emit a helper that provides .default, and it lets the type checker accept the default import.
Exercise
Your build reports Cannot redeclare block-scoped variable 'config' for two different files that each declare const config = ... and have no imports or exports. What causes it, and what is the smallest fix in each file?
Show answer
Files with no top-level import or export are scripts, so their top-level declarations share one global scope and collide. Add export {}; to each file (or give each file a real export) so it becomes a module with its own scope.