← Back to all tutorials

Modules

Organize your TypeScript code into modules using import and export.

Modules

Modules let you split your code into separate files and import/export between them.

Setting Up Modules

In tsconfig.json, set the module type:

{
  "compilerOptions": {
    "module": "ES2015",
    "target": "ES2016"
  }
}

In your HTML, use type="module":

<script type="module" src="dist/index.js"></script>

Exporting

// src/Invoice.ts
export class Invoice {
    constructor(
        readonly client: string,
        private details: string,
        public amount: number
    ) {}

    format(): string {
        return `${this.client} owes $${this.amount} for ${this.details}`;
    }
}

Importing

// src/index.ts
import { Invoice } from "./Invoice.js";

const inv = new Invoice("Mario", "website", 250);
console.log(inv.format());

Note: When importing, use the .js extension (the compiled output), not .ts.

Multiple Exports

// src/utils.ts
export const taxRate = 0.2;

export const calculateTax = (amount: number): number => {
    return amount * taxRate;
};

// src/index.ts
import { Invoice } from "./Invoice.js";
import { taxRate, calculateTax } from "./utils.js";

Default Exports

// src/Invoice.ts
export default class Invoice { ... }

// src/index.ts
import Invoice from "./Invoice.js";

Key Takeaways

  • Use export to make classes/functions available to other files
  • Use import { Name } to bring them in
  • Import with .js extension for the compiled output
  • Add type="module" to your HTML script tag