08 modules and config

A file with an export is a module A file without one is a script and its declarations are global That distinction causes more confusion than it should

Table of Contents

ESM

export const version = "1.0";
export type Result<T, E> = { ok: true; value: T } | { ok: false; error: E };

export type emits nothing at runtime export const does Use export type when a consumer only needs the shape

Import with import { thing } from "./file.js" The .js extension in source is correct when the output is ESM The compiler rewrites nothing about that path

CJS

--module commonjs is the flag name from tsc --help Use it when the runtime expects require() --esModuleInterop eases mixing default imports with CommonJS modules

Declaration files

tsc --declaration --emitDeclarationOnly

Both flags were confirmed in tsc --help The output is a .d.ts file with types and no JavaScript Publish that alongside the package so consumers get completions

tsconfig

tsconfig.json is the project-level version of the CLI flags above The handbook has a dedicated reference page for every key Start with strict: true , target: ES2022 , and an explicit lib

Do not copy a config from a framework template without reading it Half the “TypeScript is broken” reports I see are a copied config with the wrong module resolution

Common errors

  • File is not a module -> add an export
  • Cannot find module -> wrong path or missing type declarations for a JS package
  • Duplicate identifier -> two script files declaring the same global name

Posted