Check JavaScript Runtime Environment With Environment.js

Category: Javascript , Recommended | May 14, 2024
Author:sindresorhus
Views Total:7 views
Official Page:Go to website
Last Update:May 14, 2024
License:MIT

Preview:

Check JavaScript Runtime Environment With Environment.js

Description:

Environment.js is a lightweight JavaScript library that helps developers identify the runtime environment their code is executing in:

  • Browser
  • Node
  • Bun
  • Deno
  • Electron
  • JsDom
  • WebWorker
  • DedicatedWorker
  • SharedWorker
  • ServiceWorker
  • OS (macOS, iOS, Windows, etc)

This library can be useful when you need to use environment-specific features or handle differences in browser and server-side environments. For instance, a script meant for Node.js may fail or behave unpredictably if run in a browser. Environment.js can help you avoid errors and ensure your application behaves as expected across various platforms.

How to use it:

1. Install & download the Environment package with NPM.

npm install environment

2. Import the specific modules you need into your project.

import {
  isBrowser, 
  isNode,
  isBun,
  isDeno,
  isElectron,
  isJsDom,
  isWebWorker,
  isDedicatedWorker,
  isSharedWorker,
  isServiceWorker,
  isMacOs,
  isWindows,
  isLinux,
  isIos,
  isAndroid
} from 'environment';

3. Check the environment and execute environment-specific code as shown below:

if (isBrowser) {
  // do something if is running in a browser
}
// add additional checks as needed for other environments

Changelog:

v1.1.0 (05/14/2024)

  • Add some operating system checks (macOS, iOS, Windows, etc)

You Might Be Interested In:


Leave a Reply