Type Only Imports Keep Runtime Lean
Keep type-only imports erased from the runtime output with import type, while value imports stay real and usable at execution time.
Code
import type { Stats } from 'node:fs';
import { statSync } from 'node:fs';
// import type 声明纯类型导入:编译擦除,不进运行时;
// verbatimModuleSyntax 开启后,类型与值混用必须这样分开写
function describe(path: string): string {
const stats: Stats = statSync(path);
return stats.isDirectory() ? 'directory' : 'file';
}
// 值导入照常参与运行时:Stats 只出现在类型位置
const cwd: Stats = statSync('.');
const binary: Stats = statSync(process.execPath);
console.log('cwd is a', describe('.'));
console.log('binary is a', describe(process.execPath));
console.log('cwd dir?', cwd.isDirectory(), '| binary file?', binary.isFile());
console.log('binary size bytes:', binary.size > 0);What the code does
Type Only Imports Keep Runtime Lean keeps everything in the function describe.
statSync comes from node:fs — Node.js core modules the runtime ships with.
Caveats
- The only import,
node:fs, is part of the Node.js standard library.
Applying it
Entry signature: function describe(path: string)
The demo output is labeled (cwd is a, binary is a, cwd dir?), so the printed lines read as a per-operation trace of the run.
Statements that matter
return stats.isDirectory() ? 'directory' : 'file';
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The imports resolve to Node.js core modules, which the runtime provides.
Report a problem with this exampleOpens a pre-filled issue on GitHub.