xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

如何判断当前 js 代码是运行在浏览器还是node环境中 All In One

如何判断当前 js 代码是运行在浏览器还是node环境中 All In One

globalThis

// ✅✅✅
const env = globalThis.window ? 'js 运行在浏览器环境' : 'js 运行 Node.js 环境';

console.log('js env =', env);

console.log('js env =', globalThis.window);
// undefined
console.log('js env =', typeof window);
// string  'undefined'
console.log('js env =', typeof global);
// 'object'

/*

js env = js 运行 Node.js 环境
js env = undefined
js env = 'undefined'
js env = 'object'

*/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis

puppeteer & isNode

https://github.com/puppeteer/puppeteer/blob/main/src/environment.ts

export const isNode = !!(typeof process !== 'undefined' && process.version);

solutions ✅

// ✅✅
// const env = (typeof window === 'object') ? 'js 运行在浏览器环境' : 'js 运行 Node.js 环境';
const env = (typeof window === 'undefined') ? 'js 运行在浏览器环境' : 'js 运行 Node.js 环境';

console.log('js env =', env);

console.log('!!(typeof window) =', !!(typeof window));
console.log('(typeof window === \'undefined\') =', typeof window === 'undefined');

/*

js env = js 运行在浏览器环境
!!(typeof window) = true
(typeof window === 'undefined') = true

*/

// ✅
let env = 'js 运行 Node.js 环境';
try {
  if(window) {
    env = 'js 运行在浏览器环境';
  }
} catch (error) {
  // console.log('error =', error);
}
console.log('js env =', env);

bad

const env = window ? 'js 运行在浏览器环境' : 'js 运行 Node.js 环境';

console.log('js env =', env);

/*

const env = window ? 'js 运行在浏览器环境' : 'js 运行 Node.js 环境';
            ^
ReferenceError: window is not defined

*/


const env = global ? 'js 运行在浏览器环境' : 'js 运行 Node.js 环境';

console.log('js env =', env);

/*
// Uncaught ReferenceError: global is not defined

*/

refs



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-01-16 23:08  xgqfrms  阅读(796)  评论(4编辑  收藏  举报