如何判斷當前 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, 禁止轉載 🈲️,侵權必究⚠️!



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM