In creating packages with the isolatedModules option enabled, specific TypeScript compilation rules must be followed. This is because the isolatedModules flag forces files to be transpiled as separate modules, meaning each file must compile independently without dependencies on other files. Below are key points and steps to consider when creating packages in this mode:
1. Understanding the Limitations of isolatedModules
- Cannot use non-type re-exports; for example,
export { x } from './module'must be changed toimport { x } from './module'; export { x }; - Cannot declare
constenums without initialization. - Cannot use
namespaceas they cannot be correctly transpiled into a module.
2. Modular Design
Due to the requirement for independent compilation, design should aim for low module coupling. This enhances code maintainability and testability. For example:
typescript// utils.ts export function add(a: number, b: number): number { return a + b; } // index.ts import { add } from './utils'; export function total(a: number, b: number, c: number): number { return add(add(a, b), c); }
3. Using Explicit Type Imports and Exports
In isolatedModules mode, ensure all imports and exports explicitly specify whether they are types or values. For example, use import type { SomeType } from './types'; to import types.
4. Writing Independent Tests
Write separate unit tests for each module to ensure they run independently of other modules. This not only satisfies the isolatedModules requirement but also supports high-quality code.
5. Building and Bundling
Use build tools like Webpack or Rollup to ensure each module is processed correctly. Configuration may require special attention to module dependencies and bundling strategies.
Example
Suppose we want to create a math utility library; the code can be organized as follows:
typescript// mathUtils.ts export function add(x: number, y: number): number { return x + y; } // index.ts import { add } from './mathUtils'; export function sumOfArray(arr: number[]): number { return arr.reduce((acc, val) => add(acc, val), 0); }
In this example, mathUtils.ts and index.ts are fully independent modules that can be compiled separately, and when using functions from mathUtils.ts in index.ts, the correct import and export approach is applied.
Overall, by following these principles and steps, you can effectively create and manage TypeScript packages with the isolatedModules option enabled.