React的exenv模块简析

问题1:为什么要使用exenv模块

React的ExecutionEnvironment模块被单独抽取出来,用于在其他组件或者包中使用,其简单用法如下:

var ExecutionEnvironment = require('exenv');
// You now have...
ExecutionEnvironment.canUseDOM             // is the DOM available? i.e window document etc. 
ExecutionEnvironment.canUseWorkers         // are Web Workers available?
ExecutionEnvironment.canUseEventListeners  // are Events available? i.e addEventListener etc.
ExecutionEnvironment.canUseViewport        // is there a viewport? i.e window.screen
在React的0.13中的ExecutionEnvironment包中包含了一个isInWorker属性,其值为!canUseDOM(如果在worker线程中,那么是不能操作DOM的),但是因为其只用于React的内部,同时有点hack的味道,无法用于其他的模块,所以后来被废弃掉了。虽然很多包和组件都使用React私有的ExecutionEnvironment库去检测一些特性,特别是服务端渲染。例如:
canUseDOM = require('react/lib/ExecutionEnvironment').canUseDOM; // BAD

但是使用这种React内部方法的方式并非最佳实践,因为在未来很可能被废弃掉
 
问题2:其内部是如何检测我们需要的特性的,如canUseDOM等

/*!
  Copyright (c) 2015 Jed Watson.
  Based on code that is Copyright 2013-2015, Facebook, Inc.
  All rights reserved.
*/
/* global define */

(function () {
	'use strict';

	var canUseDOM = !!(
		typeof window !== 'undefined' &&
		window.document &&
		window.document.createElement //window,window.document,window.document.createElement同时存在
	);

	var ExecutionEnvironment = {
		canUseDOM: canUseDOM,
		canUseWorkers: typeof Worker !== 'undefined',//在检测浏览器的webworker使用就是采用这种方式

		canUseEventListeners:
			canUseDOM && !!(window.addEventListener || window.attachEvent),

		canUseViewport: canUseDOM && !!window.screen //判断window.screen是否存在

	};

	if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
		define(function () {
			return ExecutionEnvironment;
		});
	} else if (typeof module !== 'undefined' && module.exports) {
		module.exports = ExecutionEnvironment;
	} else {
		window.ExecutionEnvironment = ExecutionEnvironment;
	}

}());

上面的代码应该很容易看懂,此处不做分析

参考资料:

React的exenv模块

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值