React的exenv模块简析

来源:互联网 发布:ant编译java文件 编辑:程序博客网 时间:2024/05/22 15:25

问题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 0
原创粉丝点击