如何判斷當前 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

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, 禁止轉載 🈲️,侵權必究⚠️!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章