- Notifications
You must be signed in to change notification settings - Fork8
EnvironmentDetection
uupaa edited this pageMay 19, 2017 ·30 revisions
WebModule が直接的にサポートしている環境における特徴点を洗い出したものが以下の表になります。
Browser | ESModules | Worker | Node.js | NW.js | Electron render | Electron main | |
---|---|---|---|---|---|---|---|
typeof this | object | - | - | - | object | object | - |
typeof window | object | object | - | - | object | object | - |
typeof self | object | object | object | - | object | object | - |
typeof global | - | - | - | object | object | object | object |
typeof GLOBAL | - | - | - | object | - | object | object |
typeof document | object | object | - | - | object | object | - |
typeof WorkerLocation | - | - | object | - | - | - | - |
typeof __dirname | - | - | - | string | - | string | string |
typeof __filename | - | - | - | string | - | string | string |
setTimeout + "" | native | native | native | !native | native | native | !native |
process.type | - | - | - | - | - | "renderer" | "browser" |
このパズルを解き、コンパクトにまとめたものがWebModule.js の冒頭にある動作環境判別コードになります。
varGLOBAL=(this||0).self||(typeofself!=="undefined") ?self :global;// --- environment detection -------------------------------// https://github.com/uupaa/WebModule/wiki/EnvironmentDetection(function(){varhasGlobal=!!GLOBAL.global;// Node.js, NW.js, ElectronvarprocessType=!!(GLOBAL.process||0).type;// Electron(render and main)varnativeTimer=!!/native/.test(setTimeout);// Node.js, Electron(main)GLOBAL.IN_BROWSER=!hasGlobal&&"document"inGLOBAL;// Browser and WorkerGLOBAL.IN_WORKER=!hasGlobal&&"WorkerLocation"inGLOBAL;// WorkerGLOBAL.IN_NODE=hasGlobal&&!processType&&!nativeTimer;// Node.jsGLOBAL.IN_NW=hasGlobal&&!processType&&nativeTimer;// NW.jsGLOBAL.IN_EL=hasGlobal&&processType;// Electron(render and main)})();
- ブラウザ(Browser, Worker) でIN_BROWSER が true になります
- Worker でIN_WORKER が true になります
- Node.js でIN_NODE が true になります
- NW.js でIN_NW が true になります
- Electron でIN_EL が true になります
IN_xxx はグローバル変数として export されます。これらを参照することで、それぞれの環境に適したコードを簡単に記述できます。
if(IN_EL||IN_NW){ ...}elseif(IN_BROWSER){ ...}