Envify: Environment Variable Replacement
Envify is a Browserify transform that selectively replaces Node.js-style environment variables (e.g., `process.env.NODE_ENV`) with plain string literals during the bundling process. This optimization is crucial for front-end applications, as it allows tools like UglifyJS to perform dead-code elimination, significantly reducing bundle size by stripping out environment-specific code paths (e.g., development-only logging). The package is currently at version 4.1.0 and, while mature and stable, its release cadence is infrequent, reflecting its maintenance status rather than active development. Key differentiators include its tight integration with Browserify's transform pipeline and its ability to purge unused `process.env` references to avoid including Browserify's `process` shim, further optimizing bundle size. It supports both using the system's `process.env` or providing a custom environment object.
Common errors
-
ReferenceError: process is not defined
cause The `process` object is a Node.js global. In a browser environment without `envify` replacing `process.env` references, Browserify includes a shim for `process` by default. If `envify` hasn't fully replaced all `process.env` references and the `purge` option isn't used, or if `process` is accessed directly for non-environment variables, this error can occur.fixEnsure `envify` is correctly applied as a Browserify transform. Use the `purge` option (e.g., `-t [ envify purge --NODE_ENV production ]` or `{ _: 'purge' }` in the API) to replace any remaining `process.env.VAR` references with `undefined`. Avoid direct references to `process` in browser code unless specifically polyfilled. -
Error: Cannot find module 'envify'
cause The `envify` package is not installed or not discoverable in your project's `node_modules`.fixRun `npm install envify` or `yarn add envify` in your project directory. If using it globally via CLI, run `npm install -g envify`.
Warnings
- breaking Older versions of Browserify might not support the subarg syntax for passing custom environment variables or the `purge` option directly via the CLI. Ensure Browserify is at least v3.25.0 for full CLI feature support.
- gotcha By default, `envify` only replaces environment variables that are explicitly defined in the `process.env` object or passed to `envify/custom`. Undefined variables are left as `process.env.VAR_NAME`, potentially causing Browserify to include its ~2KB `process` shim in the bundle.
- gotcha Environment variables are replaced with their *string* values. Comparisons like `process.env.VAR === 1` will become `'value' === 1`, which evaluates differently than `undefined === 1`. Always ensure your comparisons match the string replacement behavior.
- gotcha Envify only processes `process.env.VAR_NAME` syntax. If you are accessing environment variables in other ways (e.g., `process.env['VAR_NAME']` or `const env = process.env; env.VAR_NAME`), these patterns might not be transformed, leading to unexpected behavior or larger bundle sizes.
Install
-
npm install envify -
yarn add envify -
pnpm add envify
Imports
- envify
const envify = require('envify');import envify from 'envify';
- customEnvify
const customEnvify = require('envify').custom;import customEnvify from 'envify/custom';
- EnvifyTransform
b.transform('envify');b.transform(envify());
Quickstart
import browserify from 'browserify';
import envify from 'envify';
import fs from 'node:fs';
import path from 'node:path';
const mainJsContent = `
if (process.env.NODE_ENV === "development") {
console.log('development only debug log');
}
if (process.env.FEATURE_FLAG === "enabled") {
console.log('Feature A is enabled!');
}
console.log('This always runs.');
`;
const outputDir = path.join(process.cwd(), 'temp_build');
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
const mainJsPath = path.join(outputDir, 'main.js');
fs.writeFileSync(mainJsPath, mainJsContent);
// Bundle for production
const b = browserify(mainJsPath);
b.transform(envify({
NODE_ENV: 'production',
FEATURE_FLAG: 'disabled',
_: 'purge' // Purge undefined process.env references
}));
const productionBundlePath = path.join(outputDir, 'bundle.production.js');
b.bundle().pipe(fs.createWriteStream(productionBundlePath))
.on('finish', () => {
console.log(`Production bundle created at: ${productionBundlePath}`);
console.log('Content (simplified):');
console.log(fs.readFileSync(productionBundlePath, 'utf8').substring(0, 200) + '...');
// Expected: console.log('This always runs.'); without development/feature logs
});
// Example of development bundle (for demonstration, showing code NOT removed)
const bDev = browserify(mainJsPath);
bDev.transform(envify({
NODE_ENV: 'development',
FEATURE_FLAG: 'enabled'
}));
const developmentBundlePath = path.join(outputDir, 'bundle.development.js');
bDev.bundle().pipe(fs.createWriteStream(developmentBundlePath))
.on('finish', () => {
console.log(`\nDevelopment bundle created at: ${developmentBundlePath}`);
console.log('Content (simplified):');
console.log(fs.readFileSync(developmentBundlePath, 'utf8').substring(0, 200) + '...');
// Expected: both console.logs visible
});