babel-plugin-transform-define
raw JSON →A Babel plugin for compile-time replacement of identifiers, member expressions, and typeof statements, similar to Webpack's DefinePlugin. The current stable version is 2.1.4 (released 2024-12-12), with a slow, maintenance-focused release cadence. Unlike Webpack's DefinePlugin which operates at the bundler level, this plugin works at the Babel transpilation stage, making it useful for library authors who want to define compile-time constants without a bundler. Key differentiator: supports replacing typeof expressions (e.g., "typeof window": "object") and member expressions (e.g., "process.env.NODE_ENV": "production"). Notable changes: v2.1.3 avoids replacing object keys to prevent bugs; v2.1.4 also prevents object property replacement. Maintenance status is stable, with no active feature development but continued bug/security fixes.
Common errors
error Error: Cannot find module 'babel-plugin-transform-define' ↓
error TypeError: Cannot read properties of undefined (reading 'includes') ↓
error The plugin 'transform-define' collides with another plugin or preset. Make sure that the order of plugins is correct. ↓
error Unexpected token: operator ↓
Warnings
gotcha Object keys are not replaced. Before v2.1.3, keys inside object literals could be unintentionally replaced, causing bugs. ↓
gotcha Object properties are not replaced. After v2.1.4, even property access expressions on objects are not replaced to avoid unintended side effects. ↓
deprecated The plugin is in maintenance mode (stable). No new features planned, but bug fixes and security patches continue. ↓
gotcha Replacement values must be strings (or numbers/booleans) – objects or functions are not supported and will cause issues. ↓
Install
npm install babel-plugin-transform-define yarn add babel-plugin-transform-define pnpm add babel-plugin-transform-define Imports
- default plugin wrong
import plugin from 'babel-plugin-transform-define'correctno import needed; use in Babel config: ["transform-define", { ... }] - Babel config usage (JavaScript) wrong
require('babel-plugin-transform-define') in codecorrectmodule.exports = { plugins: [['transform-define', { 'process.env.NODE_ENV': 'production' }]] } - Babel config usage (JSON) wrong
using require() in JSONcorrect{"plugins": [["transform-define", {"process.env.NODE_ENV": "production"}]]}
Quickstart
// Install: npm install --save-dev babel-plugin-transform-define
// .babelrc.js
const overrides = { 'DEBUG': 'true' };
module.exports = {
plugins: [
['transform-define', {
'process.env.NODE_ENV': 'production',
'typeof window': 'object',
...overrides
}]
]
};
// Input
VERSION = '1.0.0';
if (process.env.NODE_ENV === 'production') {
console.log('Release');
}
// Output (after Babel)
"1.0.0";
if (true) {
console.log('Release');
}