TypeScript Module Patterns

VerifiedSafe

Organize TypeScript code with ES modules, barrel exports, path aliases, and declaration files.

Sby Skills Guide Bot
DevelopmentIntermediate
7/27/2026
Claude CodeCursorWindsurfCopilotCodex
#typescript#es-modules#path-aliases#project-structure#declaration-files

Recommended for

Automated summary

This skill lays out concrete conventions for organizing TypeScript code with ES modules: named exports, barrel files, path aliases, and declaration files.

Strengths

  • Provides copy-paste-ready code samples for named exports, barrels, `import type` / `export type`, and namespace imports
  • Flags the common trap that tsconfig `paths` aliases must also be mirrored in the bundler (Vite, webpack, Next.js)
  • Honestly covers barrel trade-offs (clean public API vs. tree-shaking) and gives practical tactics for breaking circular imports
  • Includes package.json `exports` entry points for library projects

Limitations

  • It is a conventions checklist: no scripts, lint rules, or automated checks are supplied to enforce it
  • The trade-offs section is cut off and `moduleResolution` is only skimmed, without a complete config example
  • Does not address CommonJS/ESM interop or workspace resolution in a monorepo
When to use it

Use it when setting up or reorganizing a TypeScript project's import architecture, or when you want a clean public API through barrel files.

When not to use it

Skip it for plain JavaScript codebases or a single isolated file where these architecture conventions add no value.

Security analysis

Safe
Quality score88/100

This is a pure reference document about TypeScript module organization. It declares no tools, contains no executable instructions, no network calls, no file-system mutations, and no credential handling. All code blocks are illustrative TypeScript/JSON snippets for imports, exports, and tsconfig settings.

No concerns found

How this analysis is made

Examples

Set up feature barrels and aliases
Set up barrel index.ts files at my feature boundaries and configure @/* path aliases in tsconfig.json, plus the matching Vite resolve.alias config.
Fix circular imports
My auth and user modules import from each other and TypeScript is complaining. Restructure them to remove the circular dependency using shared type modules and import type.
Type an untyped JS package
Write a .d.ts declaration file for this untyped legacy JS module so I can import it with full types.

TypeScript Module Patterns

Organize TypeScript code with ES modules, barrel exports, path aliases, and declaration files

When to Use

  • Structuring a TypeScript project's import/export architecture
  • Setting up barrel files (index.ts re-exports) for clean public APIs
  • Configuring path aliases to avoid deep relative imports
  • Creating or consuming declaration files (.d.ts)

Instructions

  1. Use named exports over default exports for better refactoring and tree-shaking:
// user.ts
export interface User {
  id: string;
  name: string;
}
export function createUser(name: string): User {
  /* ... */
}

// consumer.ts
import { User, createUser } from './user';
  1. Barrel files — re-export from index.ts to create clean module boundaries:
// features/auth/index.ts
export { AuthProvider } from './auth-provider';
export { useAuth } from './use-auth';
export type { AuthState, AuthAction } from './types';

// Consumer imports from the module, not internal files
import { AuthProvider, useAuth } from '@/features/auth';
  1. Configure path aliases in tsconfig.json:
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"],
      "@/db/*": ["src/db/*"],
      "@/lib/*": ["src/lib/*"]
    }
  }
}

Mirror in your bundler config (Next.js, Vite, etc.) so runtime resolution matches TypeScript's.

  1. export type for type-only exports — prevents runtime import of type-only modules:
export type { User, Post } from './types';
export { createUser } from './user';
  1. import type for type-only imports:
import type { User } from './types';
import { createUser } from './user';

Enable verbatimModuleSyntax in tsconfig to enforce this distinction.

  1. Declaration files (.d.ts) — provide types for JavaScript modules:
// legacy-module.d.ts
declare module 'legacy-module' {
  export function doWork(input: string): number;
  export interface Config {
    verbose: boolean;
  }
}
  1. Namespace imports for modules with many exports:
import * as Schema from '@/db/schema';

const user = Schema.users;
const post = Schema.posts;
  1. Avoid circular imports — if module A imports from B and B imports from A:

    • Extract shared types into a separate module C
    • Use import type when only types are needed (type imports are erased and do not cause runtime circularity)
    • Restructure to unidirectional dependencies
  2. Package entry points — configure exports in package.json for library projects:

{
  "exports": {
    ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
    "./utils": { "types": "./dist/utils.d.ts", "import": "./dist/utils.js" }
  }
}

Details

TypeScript modules follow the ES module standard. Each file with a top-level import or export is a module; files without them are scripts (global scope).

verbatimModuleSyntax (recommended): Forces you to use import type for type-only imports and export type for type-only re-exports. This eliminates ambiguity about which imports are erased during compilation.

Barrel file trade-offs:

  • Pros: Clean public API, consumers do not depend on internal file structure
  • Cons: Can defeat tree-shaking in some bundlers (import from barrel loads entire module), can create large import chains
  • Best practice: Use barrels at feature boundaries, not for every directory

Path aliases require bundler sync: TypeScript's paths only affect type checking. The runtime module resolver (Node.js, Vite, webpack) must also be configured to resolve the same aliases.

moduleResolution options:

  • node — traditional Node.js resolution (index.ts, package.json main)
  • node16 / nodenext — Node.js ESM resolution (requires file extensions in imports)
  • bundler — modern bundler resolution (Vite, webpack, esbuild). Best choice for most frontend projects

Trade-offs:

  • Barrel files improve DX but can hurt bundle size — profile with your bundler's analysis tool
  • Path aliases improve readability but add configuration overhead in every tool that processes imports
  • verbatimModuleSyntax catches real bugs but requires existing code to be updated with import type

Source

https://typescriptlang.org/docs/handbook/modules.html

Process

  1. Read the instructions and examples in this document.
  2. Apply the patterns to your implementation, adapting to your specific context.
  3. Verify your implementation against the details and edge cases listed above.

Harness Integration

  • Type: knowledge — this skill is a reference document, not a procedural workflow.
  • No tools or state — consumed as context by other skills and agents.

Success Criteria

  • The patterns described in this document are applied correctly in the implementation.
  • Edge cases and anti-patterns listed in this document are avoided.

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/typescript-module-patterns-ms2s7cfg/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/typescript-module-patterns-ms2s7cfg' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/typescript-module-patterns-ms2s7cfg/download' --output '.skill-downloads/typescript-module-patterns-ms2s7cfg/SKILL.md.part' && mv '.skill-downloads/typescript-module-patterns-ms2s7cfg/SKILL.md.part' '.skill-downloads/typescript-module-patterns-ms2s7cfg/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

This file does not provide a usable name/description header for this native procedure. It remains available to download and inspect; use the manual method below.

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/typescript-module-patterns-ms2s7cfg/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills