import defer for lazy module evaluation
Use TypeScript's import defer syntax to move module evaluation from startup to the first namespace property read.
Your command-line tool has a report mode. The report module builds a lookup table at the top of the file, so a plain static import makes that work part of startup. With import defer, the branch that reads the report export can pay for the work.
Make the order visible
Save this as report.ts. The log stands in for top-level work in a real report module.
console.log('report: initialize')
const labels = new Map([[200, 'OK'], [404, 'Missing']])
export function label(status: number) {
return labels.get(status) ?? 'Unknown'
}The lookup table comes into existence when the module body runs. With a regular namespace import from a file that uses label, the initialization line appears before that file's first log.
Read the namespace inside the branch
Save this as main.ts next to it.
import defer * as report from './report.js'
console.log('main: started')
if (process.argv.includes('--report')) {
console.log(report.label(404))
}After bundling below, the program prints main: started first. If the flag is present, the property read in report.label(404) runs the module and its initialization log, then the call prints Missing.
diagram
Two evaluation orders
Keep that first read inside the branch. Destructuring const { label } = report at the start of main.ts reads a property there, so the table would be ready before you inspect the flag.
Run it through a bundler that supports it
TypeScript 5.9 added support for the namespace form. Use module: esnext or module: preserve to keep the syntax in the emitted JavaScript. A runtime or bundler still needs to implement it.
Use a standalone package without a tsconfig.json for this example. With TypeScript 5.9 or later, @types/node, and Webpack with experiments.deferImport support installed, run this from the directory containing both TypeScript files.
pnpm exec tsc --module esnext --moduleResolution bundler --target es2022 --types node --outDir compiled main.ts report.tsSave this as bundle.cjs in the same directory.
const webpack = require('webpack')
webpack({
mode: 'development',
devtool: false,
target: 'node',
context: __dirname,
entry: './compiled/main.js',
experiments: { deferImport: true },
output: { filename: 'report.cjs' },
}, (error, stats) => {
if (error || stats.hasErrors()) {
console.error(error ?? stats.toString({ all: false, errors: true }))
process.exitCode = 1
}
})After node bundle.cjs, compare node dist/report.cjs with node dist/report.cjs --report. The first run prints the startup line by itself. The flag adds the initialization and lookup result.
The Webpack experiment delays evaluation in this example while keeping the report in the bundle. If your goal is to fetch a separate chunk on demand, use import() inside the branch and check your bundler's output.