Detect Bundler Environment

1.1.0 · active · verified Tue Apr 21

The `detect-bundler` package provides build-time flags to identify if the current code is being bundled for a web browser (e.g., via Webpack, Browserify) or for React Native (via Metro). Unlike runtime environment detection, this library leverages the `package.json` `browser` field specification to resolve platform-specific code paths during the build process, ensuring zero runtime overhead. Its current stable version is 1.1.0. Given its focused utility, new releases are infrequent and primarily address minor updates or compatibility fixes rather than new features. This design choice makes it particularly useful for libraries or applications needing to conditionally include platform-specific logic without impacting runtime performance, differentiating it from solutions that rely on `navigator` or `process` checks.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates importing and using the `isBrowser` and `isReactNative` flags to conditionally execute platform-specific code at build time.

import { isBrowser, isReactNative } from 'detect-bundler';

// This code demonstrates how to use the build-time detection flags.
// The values of isBrowser and isReactNative are determined by your bundler
// and package.json 'browser' field configuration at build-time.
// They are static constants in the final bundled output.

if (isBrowser) {
  console.log('Running in a browser environment (detected at build time).');
  // Perform browser-specific initialization, e.g., accessing DOM
  // document.body.classList.add('is-browser');
} else if (isReactNative) {
  console.log('Running in a React Native environment (detected at build time).');
  // Perform React Native-specific initialization
  // import { Platform } from 'react-native';
  // if (Platform.OS === 'ios') { /* ... */ }
} else {
  console.log('Running in a Node.js-like or other environment.');
  // Perform Node.js or universal initialization
  console.log(`Current environment variable example: ${process.env.NODE_ENV ?? 'undefined'}`);
}

// Example of conditional export based on detection
export const platformSpecificMessage = isBrowser
  ? 'Hello from the Web!'
  : isReactNative
    ? 'Hello from React Native!'
    : 'Hello from Node.js!';

console.log(platformSpecificMessage);

view raw JSON →