实现说明
逻辑主体由函数 runtimeName承担。
使用要点
- 浏览器才是这里的运行环境:
window在 Node 里拿不到。 - 守卫
typeof g.process !== 'undefined' && g.process.versions?.node满足时靠提前的return短路流程。
常见问题
「globalThis 探测运行环境」能在裸 Node.js 里跑吗?
不能——这类 API 归浏览器环境所有(window),Node 里不存在。请在页面或 DevTools 控制台中运行。
主要签名是 function runtimeName()
核心语句
if (typeof g.process !== 'undefined' && g.process.versions?.node) {
return 'node';
}
return 'browser';
return 'worker';
代码示例
// globalThis is the one global reference that exists in every realm —
// window in browsers, global in Node, self in workers — so runtime
// detection can be written once and typed the same everywhere.
function runtimeName(): 'node' | 'worker' | 'browser' {
const g = globalThis as typeof globalThis & {
process?: { versions?: { node?: string } };
window?: unknown;
self?: unknown;
};
if (typeof g.process !== 'undefined' && g.process.versions?.node) {
return 'node';
}
if (typeof g.self !== 'undefined' && typeof g.window === 'undefined') {
return 'worker';
}
return 'browser';
}
const runtime = runtimeName();
console.log(runtime);
console.log(typeof globalThis);
console.log(typeof window);