Compile-time `with` for strict mode JavaScript

7.0.2 · active · verified Sun Apr 19

The `with` package provides a utility to transform JavaScript code, effectively simulating the behavior of the deprecated `with` statement at compile time. This allows developers to safely use `with`-like scoping in strict mode environments and ensures compatibility with minification tools, which typically struggle with native `with`. Currently at version 7.0.2, the package maintains an active release cadence with minor bug fixes and performance improvements following major version updates. Key differentiators include its strict mode compatibility, predictable variable assignment within the generated scope (unlike native `with` which can leak assignments), and the explicit declaration of all non-excluded variables, enabling `if (foo === undefined)` checks. It also offers detailed parsing errors for easier debugging.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic usage of `addWith` to generate strict-mode-safe `with` statements, including the `exclude` option.

import addWith from 'with';

// Basic usage: injects 'obj' properties into scope
const code1 = addWith('obj', 'console.log(a)');
console.log('// Code 1:\n', code1);
// Expected output (simplified for brevity): ';(function (console, a) { console.log(a) }(...));'

// Usage with exclusion: 'console' is treated as global/external
const code2 = addWith('obj', 'console.log(a)', ['console']);
console.log('\n// Code 2:\n', code2);
// Expected output (simplified for brevity): ';(function (a) { console.log(a) }(...));'

// Example of how the generated code behaves differently from native `with`
const generatedCodeExample = `
  const outerFoo = 'original';
  const obj = { foo: 'objFoo' };

  const addWithResult = addWith('obj', 'foo = \'modified\';', []);
  // To run this, you'd typically need a code execution context like a VM or eval
  // For demonstration, let's just log the expected behavior difference.

  // If this were native 'with (obj) { foo = 'modified'; }', 
  // obj.foo would become 'modified'.
  // With compile-time 'with', `foo` becomes a local variable within the generated scope,
  // and assignments to `foo` do not affect `obj.foo` or `outerFoo`.
`;
console.log('\n// Example illustrating behavior difference with assignments (conceptual):');
console.log(generatedCodeExample);

view raw JSON →