zoukankan      html  css  js  c++  java
  • 如何判断当前 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, 禁止转载 ️,侵权必究⚠️!


    xgqfrms
  • 相关阅读:
    python_Memcached
    python_day10_IO多路复用
    java_list,set,map集合
    python3.0_day9_scoket基础之篇
    redis.conf配置文件详解
    Java_数组
    面向接口编程初识(转)
    SSH三种框架及表示层、业务层和持久层的理解(转)
    解决win10磁盘占用过大的问题(亲测有效)
    ORA-12541:TNS:无监听程序
  • 原文地址:https://www.cnblogs.com/xgqfrms/p/15811668.html
Copyright © 2011-2022 走看看