vars-expand

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

A zero-dependency template transpiler that performs shell-like variable expansion with support for default values, alternate values, and substitution operators (:- :- :+ + :? ? etc.). Inspired by Bash's Shell Parameter Expansion syntax. Current stable version is 0.0.3, released infrequently. Key differentiators: lightweight (no dependencies), TypeScript-first with bundled typings, and full support for POSIX-style expansion patterns. Unlike general template engines (e.g., Handlebars), it strictly mirrors shell semantics, making it ideal for CI/CD pipelines, configuration loaders, and environment variable interpolation.

error TypeError: varsBraceExpand is not a function
cause CommonJS require() returns an object with default property but is not directly callable in strict ESM environments.
fix
Use import varsBraceExpand from 'vars-expand' or const { default: varsBraceExpand } = require('vars-expand').
error ReferenceError: VAR is not defined
cause Variable name in the template (${VAR}) does not exist in the data object and no default is provided.
fix
Provide a default value with ${VAR:-default} or ensure the variable exists in the data object.
error SyntaxError: Invalid or unexpected token
cause Template contains a dollar sign that JavaScript interprets as template literal interpolation. Occurs when template is defined as a template literal (backticks) without escaping.
fix
Use String.raw... or escape $ as \$ in the template string.
gotcha Empty strings are treated as set, so ${VAR:-default} will not replace an empty VAR with default. Use ${VAR:?error} to flag empty variables.
fix For empty string fallback, use ${VAR:-default} only if VAR is unset; to treat empty as unset, preprocess data or use a different operator.
gotcha Template syntax uses backtick or single-quoted strings must be careful with JavaScript template literals to avoid double interpolation. Use \${} or raw strings.
fix Use String.raw`...` or escape dollar signs in JavaScript to prevent premature interpolation.
gotcha The library only supports brace expansion syntax (${...}), not $VAR without braces. Attempting to use $VAR will leave it unexpanded.
fix Always wrap variable names in curly braces: ${VAR}, not $VAR.
npm install vars-expand
yarn add vars-expand
pnpm add vars-expand

Demonstrates shell-like variable expansion with default values using the varsBraceExpand function.

import varsBraceExpand from 'vars-expand';

const data = {
  NAME: 'Alice',
  GREETING: '',
};

const template = `Hello, ${NAME:-World}! Today is ${DAY:-Monday}.`;
const result = varsBraceExpand(template, data);
console.log(result); // 'Hello, Alice! Today is Monday.'