Modules and type-only imports

7.0.2

Modules define which types and values other files can use.

On this page

Keep type imports explicit

Use import type for declarations that are only used in type positions. It is removed from the JavaScript output. Use a normal import for values you call or read at runtime.

// product.ts
export type Product = { name: string; price: number };
export const currency = "USD";

// label.ts
import { currency } from "./product.js";
import type { Product } from "./product.js";

export function label(item: Product) {
  return item.name + ": " + currency + " " + item.price;
}

Match module settings to your runtime

Use settings that match the environment loading your files. In a Node ESM project, relative paths to compiled files normally include the .js extension. A bundler can use different resolution rules, so use the settings recommended by your build tool.

// package.json: { "type": "module" }
// tsconfig.json: { "compilerOptions": { "module": "NodeNext" } }

// format.ts
export const formatLabel = (name: string) => name.toUpperCase();

// main.ts
// The import points to format.js in the compiled output.
import { formatLabel } from "./format.js";
console.log(formatLabel("Notebook"));

Official references