Skip to content

EnvironmentDetection

uupaa edited this page May 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 の冒頭にある動作環境判別コードになります。

var GLOBAL = (this || 0).self || (typeof self !== "undefined") ? self : global;

// --- environment detection -------------------------------
// https://github.com/uupaa/WebModule/wiki/EnvironmentDetection
(function() {

var hasGlobal     = !!GLOBAL.global;              // Node.js, NW.js, Electron
var processType   = !!(GLOBAL.process || 0).type; // Electron(render and main)
var nativeTimer   = !!/native/.test(setTimeout);  // Node.js, Electron(main)

GLOBAL.IN_BROWSER = !hasGlobal && "document"       in GLOBAL;   // Browser and Worker
GLOBAL.IN_WORKER  = !hasGlobal && "WorkerLocation" in GLOBAL;   // Worker
GLOBAL.IN_NODE    =  hasGlobal && !processType && !nativeTimer; // Node.js
GLOBAL.IN_NW      =  hasGlobal && !processType &&  nativeTimer; // NW.js
GLOBAL.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) {
    ...
} else if (IN_BROWSER) {
    ...
}