Modules, Imports, and Exports
ES modules use export and import to share values and types. Use import type or export type when importing or exporting only types, especially when compiler settings preserve module syntax or your build system benefits from clear type-only imports. Type-only imports are erased from runtime output.
Module resolution is environment-sensitive. Node ESM, CommonJS, and bundler-based frontend apps have different expectations for extensions, package exports, and resolution. Follow the target platform's guidance and avoid mixing module systems casually.
Separate type and value imports
// domain.ts
export type User = { id: string; name: string };
export const defaultRole = "member";
// app.ts
import { defaultRole, type User } from "./domain.js";
const user: User = { id: "u-1", name: "Mira" };
console.log(defaultRole, user.name);💡 The
User import is used only for type checking, while defaultRole is a runtime value. The .js extension shown is appropriate in many NodeNext ESM source projects because emitted JavaScript will use that extension.Key Takeaways
- Use modules to establish clear boundaries.
- Type-only imports clarify compile-time-only dependencies.
- Match import specifiers to the project's module system.
Knowledge Check
What is the purpose of `import type`?