esbuild-ifdef

raw JSON →
0.2.0 verified Fri May 01 auth: no javascript

An esbuild plugin for compile-time conditional code inclusion/exclusion using `/// #if` comments. Current stable version: 0.2.0. Actively maintained, with a small feature set focused on preprocessor-like behavior. Key differentiators: uses triple-slash comments familiar from C/C++ preprocessors, supports nested conditionals, warnings/errors at compile time, and custom variable injection. Unlike alternatives that rely on other bundlers or complex setups, esbuild-ifdef integrates natively with esbuild and supports any JavaScript expression.

error Error: Cannot find module 'esbuild-ifdef'
cause Package not installed or missing from node_modules.
fix
Run npm install esbuild-ifdef or yarn add esbuild-ifdef.
error ifdefPlugin is not a function
cause Wrong import style; attempting to use default import instead of named export.
fix
Use import { ifdefPlugin } from 'esbuild-ifdef'.
error The plugin "ifdefPlugin" failed to initialize: ...
cause Passing invalid options or missing required `variables` object.
fix
Ensure options object has a variables property (e.g., { variables: { MY_VAR: 'value' } }).
breaking Requires esbuild ^0.15.2; incompatible with earlier or much later versions? Check peer dependency.
fix Use esbuild version matching ^0.15.2.
gotcha Default file matching regex is /\.[jt]sx?$/, which may exclude files with unknown extensions.
fix Set `filePath` option to a custom RegExp to include additional file types.
gotcha If `requireTripleSlash` is false, double-slash comments like // #if may also be processed, but they could conflict with other syntax.
fix Leave as true for clarity.
deprecated The `regExp` option overrides `requireTripleSlash`; using it incorrectly may break parsing.
fix Avoid custom regex unless you understand the default pattern.
npm install esbuild-ifdef
yarn add esbuild-ifdef
pnpm add esbuild-ifdef

Demonstrates basic usage: building with esbuild and conditionally including/excluding code via the if defined plugin.

import esbuild from 'esbuild';
import { ifdefPlugin } from 'esbuild-ifdef';

await esbuild.build({
  entryPoints: ['./src/index.js'],
  bundle: true,
  outfile: './dist/bundle.js',
  plugins: [
    ifdefPlugin({
      variables: { DEBUG: true },
    }),
  ],
});