### Unix-like Environment Example Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/is-windows.md Demonstrates the expected return value of isWindows() when running on a Unix-like operating system such as Linux or macOS. ```typescript // On Linux or macOS isWindows() // Returns: false ``` -------------------------------- ### Install cross-env with npm Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md This command installs the cross-env package using npm. ```bash npm install cross-env ``` -------------------------------- ### Typical Windows Environment Example Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/is-windows.md Demonstrates the expected return value of isWindows() when running on a standard Windows environment (cmd.exe or PowerShell). ```typescript // On Windows (cmd.exe or PowerShell) isWindows() // Returns: true ``` -------------------------------- ### Cygwin on Windows Example Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/is-windows.md Demonstrates the expected return value of isWindows() when running within Cygwin on a Windows system, where process.env.OSTYPE is 'cygwin'. ```typescript // On Windows with Cygwin (where process.env.OSTYPE === 'cygwin') isWindows() // Returns: true ``` -------------------------------- ### Basic Usage with Single Environment Variable Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/cross-env.md Spawns a Node.js process with NODE_ENV set to production. Ensure cross-env is installed. ```typescript import { crossEnv } from 'cross-env' crossEnv(['NODE_ENV=production', 'node', 'server.js']) ``` -------------------------------- ### Install cross-env for Node.js 18 or earlier Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md Use cross-env@7 for Node.js versions 18 or earlier. This command installs the specified version as a development dependency. ```bash npm install --save-dev cross-env@7 ``` -------------------------------- ### npm Script Example: Setting NODE_ENV Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/README.md This JSON configuration shows how to integrate cross-env into your project's `package.json` scripts for tasks like testing. ```json { "scripts": { "test": "cross-env NODE_ENV=test npm run test:run" } } ``` -------------------------------- ### TypeScript Usage Example Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md Demonstrates how to import and use the crossEnv function from the 'cross-env' package in a TypeScript project. It shows how to pass arguments and options, and how to access the result. ```typescript import { crossEnv, type CrossEnvOptions, type ProcessResult } from 'cross-env' const result: ProcessResult | null = crossEnv( ['NODE_ENV=test', 'npm', 'test'], { shell: true } as CrossEnvOptions ) if (result) { console.log(`Exit code: ${result.exitCode}`) } ``` -------------------------------- ### npm Scripts Usage with cross-env Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md These examples show how to use the cross-env binaries within npm scripts to set environment variables for other commands. ```json { "scripts": { "test": "cross-env NODE_ENV=test npm run test:run", "build": "cross-env NODE_ENV=production webpack" } } ``` -------------------------------- ### Install cross-env as a Dev Dependency Source: https://github.com/kentcdodds/cross-env/blob/main/README.md Install cross-env as a development dependency using npm. Ensure correct package spelling to avoid malware. Version 8 requires Node.js 20+, use version 7 for Node.js 18 or lower. ```bash npm install --save-dev cross-env ``` ```bash npm install --save-dev cross-env@7 ``` -------------------------------- ### CrossEnv Usage Examples Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/types.md Demonstrates how to use the `crossEnv` function with and without the `shell: true` option. Use `shell: true` for shell-specific syntax like pipes and chaining. ```typescript import { crossEnv } from 'cross-env' // Without shell: treats the entire string as a single command crossEnv(['NODE_ENV=test', 'npm', 'run', 'build']) // With shell: interprets shell operators and syntax crossEnv(['NODE_ENV=test', 'npm run build && npm test'], { shell: true }) ``` -------------------------------- ### Git Bash on Windows Example Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/is-windows.md Demonstrates the expected return value of isWindows() when running within Git Bash on a Windows system, where process.env.OSTYPE is 'msys'. ```typescript // On Windows with Git Bash (where process.env.OSTYPE === 'msys') isWindows() // Returns: true ``` -------------------------------- ### Cross-env Escape Sequence Example Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/OVERVIEW.md Shows how an odd number of preceding backslashes escapes a variable reference, preventing expansion. ```bash cross-env \\$VAR ``` -------------------------------- ### Split Command Execution with Environment Variables Source: https://github.com/kentcdodds/cross-env/blob/main/README.md This pattern separates environment variable setup into one script and the actual command execution into another. It's useful for managing long environment variable declarations or when you need to reuse environment configurations. ```json { "scripts": { "parentScript": "cross-env GREET=\"Joe\" npm run childScript", "childScript": "cross-env-shell \"echo Hello $GREET\"" } } ``` -------------------------------- ### Multiple Environment Variables Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/cross-env.md Sets multiple environment variables for a child process. Ensure cross-env is installed. ```typescript crossEnv(['NODE_ENV=production', 'DEBUG=false', 'node', 'app.js']) ``` -------------------------------- ### Node.js Module Resolution Examples Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md These import statements demonstrate how Node.js (version 14+) resolves modules using the 'exports' field in package.json, all pointing to the same entry point. ```typescript // All resolve to the same entry point import { crossEnv } from 'cross-env' import { crossEnv } from 'cross-env/dist/index.js' ``` -------------------------------- ### Combined Transformations Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/var-value-convert.md Shows an example where both path separator conversion and environment variable resolution are applied. This is typical for PATH variables that contain multiple directory entries separated by colons. ```typescript process.env.HOME = '/home/user' varValueConvert('$HOME:/usr/bin:/usr/local/bin', 'PATH') // On Windows: '/home/user;/usr/bin;/usr/local/bin' // On Unix: '/home/user:/usr/bin:/usr/local/bin' ``` -------------------------------- ### CrossEnv Execution Result Example Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/types.md Shows how to access and interpret the `ProcessResult` returned by `crossEnv()`. Check for `exitCode` and `signal` to understand how the process terminated. ```typescript import { crossEnv } from 'cross-env' const result = crossEnv(['NODE_ENV=test', 'npm', 'test']) if (result) { console.log(`Process exited with code: ${result.exitCode}`) if (result.signal) { console.log(`Process was killed by signal: ${result.signal}`) } } ``` -------------------------------- ### PATH Normalization on Windows Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/configuration.md cross-env normalizes the PATH separator from colons to semicolons on Windows for compatibility. This example demonstrates setting a PATH with multiple directories. ```bash # On Windows cross-env PATH=/usr/bin:/usr/local/bin node app.js # Results in PATH=/usr/bin;/usr/local/bin in the child process ``` -------------------------------- ### Windows Path Handling with cross-env Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md On Windows, cross-env automatically converts forward slashes to backslashes in PATH environment variables. This example demonstrates setting a Windows-style path. ```bash cross-env PATH=C:\Program Files\Node;C:\Windows\System32 echo test ``` -------------------------------- ### crossEnv(args, options?) Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/OVERVIEW.md Main function to set environment variables and spawn a process. It takes an array of arguments and an optional options object. ```APIDOC ## crossEnv(args, options?) ### Description Main function to set environment variables and spawn a process. ### Parameters - **args** (string[]) - Required - The command and its arguments. - **options** (CrossEnvOptions) - Optional - Configuration for the crossEnv function. ### Returns - **ProcessResult | null** - The result of the spawned process, or null if the process could not be spawned. ``` -------------------------------- ### Database Configuration Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md Set database connection parameters such as host, port, and name for migration scripts. ```bash cross-env DB_HOST=localhost DB_PORT=5432 DB_NAME=myapp npm run migrate ``` -------------------------------- ### Run Tests with npm Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/OVERVIEW.md Execute the comprehensive test suite for the cross-env project using the npm test command. ```bash npm run test ``` -------------------------------- ### Malformed Environment Variable Assignment Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/errors.md Shows how cross-env treats arguments that do not match the 'NAME=value' pattern as the start of the command, rather than throwing an error. ```typescript crossEnv(['NODE_ENV=production', 'invalid_arg', 'echo', 'hello']) ``` -------------------------------- ### Cross-env Project File Structure Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/OVERVIEW.md Illustrates the organization of the cross-env source code, including main functions, utility modules, CLI entry points, and test files. ```tree src/ index.ts # Main crossEnv function command.ts # commandConvert function variable.ts # varValueConvert and helpers is-windows.ts # isWindows function bin/ cross-env.ts # CLI: shell: false cross-env-shell.ts # CLI: shell: true __tests__/ index.test.ts # Tests for crossEnv command.test.ts # Tests for commandConvert variable.test.ts # Tests for varValueConvert is-windows.test.ts # Tests for isWindows ``` -------------------------------- ### Read OVERVIEW.md from Terminal Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/INDEX.md Use the 'cat' command to read the OVERVIEW.md file directly from your terminal. ```bash cat output/OVERVIEW.md ``` -------------------------------- ### Development vs. Production Environments Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md Set environment variables like NODE_ENV, DEBUG, and PORT to configure application behavior for development, production, or testing. ```json { "scripts": { "dev": "cross-env NODE_ENV=development DEBUG=true PORT=3000 node server.js", "prod": "cross-env NODE_ENV=production PORT=8080 node server.js", "test": "cross-env NODE_ENV=test npm run test:run" } } ``` -------------------------------- ### Cross-env Command Execution Flow Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/OVERVIEW.md Illustrates the step-by-step process cross-env follows when executing a command with environment variables. ```text User invokes: cross-env NODE_ENV=production node app.js ↓ parseCommand() splits into: - envSetters: { NODE_ENV: 'production' } - command: 'node' - commandArgs: ['app.js'] ↓ getEnvVars() applies varValueConvert() to each setter: - Resolves variable references ($VAR → actual value) - Converts path separators (PATH: → ; on Windows) ↓ commandConvert() converts command to platform syntax: - On Windows: $VAR → %VAR% - On Unix: unchanged ↓ spawn() creates child process with: - command: converted command - args: converted arguments - env: merged with system environment ↓ Signal forwarding: SIGINT, SIGTERM, SIGHUP, SIGBREAK → child ↓ Exit handler: child exit code → process.exit() ``` -------------------------------- ### Standard Command Execution Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/configuration.md Use the standard `cross-env` binary for direct command execution with environment variables. This avoids shell interpretation of commands. ```bash cross-env NODE_ENV=production npm run build ``` -------------------------------- ### Escaping Dollar Signs for Literal Values Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/configuration.md To prevent variable expansion and set a literal dollar sign, prefix the variable with a backslash. This is useful when the variable name itself starts with a dollar sign. ```bash cross-env FOO=\$BAR node app.js ``` -------------------------------- ### Basic Command-Line Usage Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/configuration.md Set a single environment variable before executing a command. This is useful for configuring application behavior like the Node.js environment. ```bash cross-env NODE_ENV=production node server.js ``` -------------------------------- ### CLI Binary: cross-env-shell Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md The `cross-env-shell` CLI binary executes commands through the system shell, similar to using `{ shell: true }`. ```APIDOC ## cross-env-shell CLI ### Description Executes commands through the system shell. ### Method CLI command ### Endpoint `cross-env-shell` ### Parameters #### Path Parameters None #### Query Parameters None #### Command Line Arguments - **args** (string[]) - Required - The command and its arguments to execute. ### Usage Example ```bash cross-env-shell NODE_ENV=test 'npm run lint && npm test' ``` ### Behavior Equivalent to `crossEnv(process.argv.slice(2), { shell: true })`. ``` -------------------------------- ### Testing with Cross-Platform Support Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md Use cross-env to set environment variables for unit, e2e, and all tests. For complex command chaining, cross-env-shell is recommended. ```json { "scripts": { "test:unit": "cross-env NODE_ENV=test vitest run", "test:e2e": "cross-env NODE_ENV=test DB_URL=sqlite:memory npm run e2e", "test:all": "cross-env-shell NODE_ENV=test 'npm run test:unit && npm run test:e2e'" } } ``` -------------------------------- ### commandConvert(command, env, normalize?) Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/OVERVIEW.md Converts a command string for the current platform, taking the command, environment variables, and an optional normalization flag. ```APIDOC ## commandConvert(command, env, normalize?) ### Description Convert command for the platform. ### Parameters - **command** (string) - Required - The command string to convert. - **env** (NodeJS.ProcessEnv) - Required - The environment variables to use. - **normalize** (boolean) - Optional - Whether to normalize the command. ### Returns - **string** - The converted command string. ``` -------------------------------- ### CLI Binary: cross-env Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md The `cross-env` CLI binary executes commands without shell interpretation, similar to using `{ shell: false }`. ```APIDOC ## cross-env CLI ### Description Executes commands without shell interpretation. ### Method CLI command ### Endpoint `cross-env` ### Parameters #### Path Parameters None #### Query Parameters None #### Command Line Arguments - **args** (string[]) - Required - The command and its arguments to execute. ### Usage Example ```bash cross-env NODE_ENV=production npm run build ``` ### Behavior Equivalent to `crossEnv(process.argv.slice(2), { shell: false })`. ``` -------------------------------- ### Read README.md from Terminal Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/INDEX.md Use the 'cat' command to read the README.md file directly from your terminal. ```bash cat output/README.md ``` -------------------------------- ### CLI: Direct Execution Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/SUMMARY.txt The primary cross-env CLI binary for direct execution of commands with environment variable management. ```bash #!/usr/bin/env node // bin/cross-env.ts require('../index.js') ``` -------------------------------- ### Handle Missing Command with cross-env Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md Demonstrates how to catch the error when no command is provided to cross-env. Ensure you import the crossEnv function. ```typescript import { crossEnv } from 'cross-env' try { crossEnv(['FOO=bar']) // No command provided } catch (error) { console.error(error.message) // "Command is required" } ``` -------------------------------- ### Main Library Export: crossEnv() Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md The main library export allows programmatic execution of commands with environment variables. It returns a ProcessResult or null. ```APIDOC ## crossEnv() ### Description Function to execute commands with environment variables. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **command** (string[]) - Required - The command and its arguments to execute. - **options** (CrossEnvOptions) - Optional - Configuration options for execution. - **shell** (boolean) - Optional - Whether to execute the command through the system shell. ### Request Example ```typescript import { crossEnv, type CrossEnvOptions, type ProcessResult } from 'cross-env' const result: ProcessResult | null = crossEnv(['NODE_ENV=test', 'npm', 'test'], { shell: false }) ``` ### Response #### Success Response (200) - **ProcessResult** (object) - An object containing information about the executed process. - **null** - If the process could not be executed. #### Response Example ```json { "status": 0, "stdout": "...", "stderr": "..." } ``` ``` -------------------------------- ### Handle No Command Provided with cross-env Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md If only environment variables are provided without a command, `crossEnv` returns `null` and no process is spawned. ```typescript const result = crossEnv(['FOO=bar']) console.log(result) // null (no process spawned) ``` -------------------------------- ### Signal Handling on Windows Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/README.md Use `cross-env-shell` for proper signal handling like Ctrl+C on Windows. This ensures that signals are correctly passed to the child process. ```bash cross-env-shell NODE_ENV=production 'node server.js' ``` -------------------------------- ### Handling Variables with Default Values in Commands Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/cross-env.md On Windows, this demonstrates handling variables with default values using the `${VAR:-default}` syntax. The `shell: true` option is required. ```typescript crossEnv(['node', '-e', 'echo ${API_URL:-http://localhost}'], { shell: true }) ``` -------------------------------- ### JSON Configuration as Environment Variable Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/configuration.md Pass complex configuration objects as JSON strings to environment variables. Ensure proper escaping for shell compatibility. ```bash cross-env TS_NODE_COMPILER_OPTIONS='{"module":"commonjs"}' ts-node file.ts ``` -------------------------------- ### Multiple Environment Variables Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/configuration.md Set multiple environment variables simultaneously before running a command. This allows for comprehensive configuration of the execution environment. ```bash cross-env NODE_ENV=production DEBUG=false PORT=3000 node app.js ``` -------------------------------- ### Chaining Multiple Commands Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md Use cross-env-shell to execute multiple commands sequentially, all within the same environment variable context. ```bash cross-env-shell NODE_ENV=test 'npm run lint && npm run test && npm run build' ``` -------------------------------- ### CLI Binary: cross-env Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/SUMMARY.txt The primary command-line interface for executing scripts with environment variables set in a cross-platform manner. ```APIDOC ## cross-env ### Description This binary allows you to run a command with environment variables defined. It automatically handles the differences in environment variable syntax between Windows and Unix-like systems. ### Usage ```bash cross-env VAR=value command ``` ### Example ```bash # Sets MY_VAR to 'Hello' and executes 'node index.js' cross-env MY_VAR=Hello node index.js # Sets multiple variables and executes a script cross-env VAR1=value1 VAR2=value2 node my_script.js ``` ``` -------------------------------- ### Unix (No Conversion) Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/command-convert.md On Unix-like systems, the command string is returned unchanged, regardless of environment variables. ```typescript commandConvert('echo $HOME', { HOME: '/home/user' }) // Returns: 'echo $HOME' (unchanged) ``` -------------------------------- ### Simple Path Conversion Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/var-value-convert.md Demonstrates how path separators are converted for PATH variables. On Windows, colons are replaced with semicolons. On Unix-like systems, the separators remain unchanged. ```typescript varValueConvert('foo:bar:baz', 'PATH') // On Windows: 'foo;bar;baz' varValueConvert('foo:bar:baz', 'PATH') // On Unix: 'foo:bar:baz' ``` -------------------------------- ### Execute Commands with Shell Interpretation (CLI) Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md Use the `cross-env-shell` CLI binary to execute commands through the system shell. This allows for shell-specific features like command chaining (`&&`) or pipes (`|`). ```bash cross-env-shell NODE_ENV=test 'npm run lint && npm test' ``` ```typescript import { crossEnv } from '../index.js' crossEnv(process.argv.slice(2), { shell: true }) ``` -------------------------------- ### Catching 'Command is required' Error Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/errors.md Demonstrates how to use a try-catch block to handle the specific error thrown when no command is provided to cross-env. ```typescript try { crossEnv(['FOO=bar']) } catch (err) { if (err instanceof Error && err.message === 'Command is required') { console.error('No command provided') } } ``` -------------------------------- ### Set Multiple Environment Variables with cross-env Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md Use this to set multiple environment variables when spawning a process. ```typescript crossEnv(['NODE_ENV=test', 'DEBUG=false', 'PORT=3000', 'node', 'app.js']) ``` -------------------------------- ### Command Conversion Utility Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/SUMMARY.txt Converts a command string to a platform-specific format, normalizing environment variables and paths. Can optionally normalize output. ```typescript commandConvert(command: string, env: NodeJS.ProcessEnv, normalize?: boolean): string ``` -------------------------------- ### Windows: Path Normalization with Variables Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/command-convert.md Combines path normalization with variable conversion. Relative paths with variables are correctly resolved and normalized on Windows. ```typescript commandConvert('./$SCRIPT', { SCRIPT: 'run.bat' }, true) // On Windows: 'run.bat' ``` -------------------------------- ### Execute Commands with Environment Variables (TypeScript) Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md Use the main library export to programmatically execute commands with specified environment variables. Configure shell interpretation using the options object. ```typescript import { crossEnv, type CrossEnvOptions, type ProcessResult } from 'cross-env' const result: ProcessResult | null = crossEnv(['NODE_ENV=test', 'npm', 'test'], { shell: false }) ``` -------------------------------- ### Windows: Multiple Variable Conversion Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/command-convert.md Multiple environment variable references within a command string are converted to Windows format on Windows. ```typescript commandConvert('cmd /c $APP_PATH --config $CONFIG_FILE', { APP_PATH: 'app.exe', CONFIG_FILE: 'config.json' }) // On Windows: 'cmd /c %APP_PATH% --config %CONFIG_FILE%' ``` -------------------------------- ### isWindows Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/README.md Detects if the current platform is Windows. ```APIDOC ## isWindows ### Description Detects if the current platform is Windows. This function accounts for environments like Git Bash and Cygwin. ### Signature ```typescript isWindows(): boolean ``` ### Return Value - **boolean** - `true` if the platform is Windows, `false` otherwise. ### Example ```javascript import { isWindows } from 'cross-env'; if (isWindows()) { console.log('Running on Windows!'); } else { console.log('Not running on Windows.'); } ``` ``` -------------------------------- ### Windows: Non-Existent Variable Handling Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/command-convert.md On Windows, undefined environment variable references are replaced with an empty string, mimicking Windows command-line behavior. ```typescript commandConvert('echo $MISSING/$HOME', { HOME: 'C:\\Users\\John' }) // On Windows: 'echo /%HOME%' (non-existent variable stripped) ``` -------------------------------- ### commandConvert Function Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/command-convert.md Converts command strings to use platform-appropriate environment variable syntax. Transforms Unix-style variable references (e.g., `$VAR`) to Windows format (e.g., `%VAR%`) on Windows platforms. Optionally normalizes the command path. ```APIDOC ## commandConvert ### Description Converts command strings to use platform-appropriate environment variable syntax. Transforms Unix-style variable references (e.g., `$VAR`) to Windows format (e.g., `%VAR%`) on Windows platforms. Optionally normalizes the command path. ### Function Signature ```typescript export function commandConvert( command: string, env: NodeJS.ProcessEnv, normalize?: boolean ): string ``` ### Parameters #### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | command | string | Yes | — | The command string to convert. May contain Unix-style environment variable references. | | env | NodeJS.ProcessEnv | Yes | — | A map of environment variable names to values. Used to resolve variable references. | | normalize | boolean | No | false | If `true`, applies `path.normalize()` to the command after conversion. Only use for commands, not command arguments. | ### Return Type `string` — The converted command string, suitable for the current operating system. ### Behavior #### Platform Detection - **On Unix/Linux/macOS**: Returns the command unchanged. - **On Windows**: Applies variable reference conversion (see below). Windows is detected by checking `process.platform === 'win32'` or `process.env.OSTYPE` matching `msys` or `cygwin`. #### Variable Reference Conversion (Windows Only) The function handles two syntax forms: 1. **Simple references**: `$VARNAME` 2. **Braced references**: `${VARNAME}` Both are converted to Windows format: `%VARNAME%` ##### Bash Parameter Expansion with Defaults If a variable reference uses the bash default syntax `${VAR:-default}`, the function applies the default if the variable is not defined: - `${HOME:-/tmp}` → If `HOME` is set, use its value; otherwise use `/tmp` This is converted to Windows format: `%HOME%` (if set) or the default value. ##### Non-Existent Variables On Windows, if a variable is undefined, the reference is replaced with an empty string rather than left as-is. This matches Windows command-line behavior where undefined variables are not expanded. Example: - Unix: `echo $UNDEFINED` prints `$UNDEFINED` literally - Windows: `echo %UNDEFINED%` prints `%UNDEFINED%` literally - cross-env on Windows: `$UNDEFINED` is stripped, result is an empty string #### Empty Variables If a variable is defined but empty, the reference is also removed (empty string replacement): - Input: `echo $EMPTY` (where `EMPTY=''`) - Output: `echo ` (the variable reference is stripped) ### Path Normalization When `normalize` is `true`, `path.normalize()` is applied after variable conversion. This is useful for commands like `./cmd.bat` which should become `cmd.bat` on Windows. - Input: `./cmd.bat` - After conversion: `./cmd.bat` (no variables to convert) - After normalization: `cmd.bat` **Note**: Normalization is only applied to the command itself, not to command arguments, to preserve relative URLs and paths in arguments. ### Examples #### Unix (No Conversion) ```typescript commandConvert('echo $HOME', { HOME: '/home/user' }) // Returns: 'echo $HOME' (unchanged) ``` #### Windows: Simple Variable Reference ```typescript commandConvert('echo $HOME', { HOME: 'C:\Users\John' }) // On Windows: 'echo %HOME%' // On Unix: 'echo $HOME' ``` #### Windows: Braced Variable Reference ```typescript commandConvert('echo ${NODE_ENV}', { NODE_ENV: 'production' }) // On Windows: 'echo %NODE_ENV%' ``` #### Windows: Multiple Variables ```typescript commandConvert('cmd /c $APP_PATH --config $CONFIG_FILE', { APP_PATH: 'app.exe', CONFIG_FILE: 'config.json' }) // On Windows: 'cmd /c %APP_PATH% --config %CONFIG_FILE%' ``` #### Windows: Bash Default Syntax ```typescript commandConvert('node ${ENTRY_POINT:-index.js}', { ENTRY_POINT: 'server.js' }) // On Windows: 'node %ENTRY_POINT%' commandConvert('node ${ENTRY_POINT:-index.js}', {}) // On Windows: 'node index.js' (default applied) ``` #### Windows: Non-Existent Variable ```typescript commandConvert('echo $MISSING/$HOME', { HOME: 'C:\Users\John' }) // On Windows: 'echo /%HOME%' (non-existent variable stripped) ``` #### Windows: Path Normalization ```typescript commandConvert('./script.bat', {}, true) // On Windows: 'script.bat' // On Unix: './script.bat' ``` #### Windows: Path Normalization with Variables ```typescript commandConvert('./$SCRIPT', { SCRIPT: 'run.bat' }, true) // On Windows: 'run.bat' ``` ``` -------------------------------- ### Handling Empty Command After Parsing Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/errors.md Illustrates a scenario where cross-env returns null without spawning a process because the command becomes empty after parsing. ```typescript crossEnv(['FOO=bar', '']) // No command, process returns null (no spawn) ``` -------------------------------- ### Read API Reference from Terminal Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/INDEX.md Use the 'cat' command to read all API reference markdown files from your terminal. ```bash cat output/api-reference/*.md ``` -------------------------------- ### Pass JSON Configuration as Environment Variable with cross-env Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md Shows how to pass structured configuration data as a JSON string to an environment variable. ```typescript const config = { module: 'commonjs', target: 'es2020' } crossEnv([ `TS_NODE_COMPILER_OPTIONS=${JSON.stringify(config)}`, 'ts-node', 'file.ts' ]) ``` -------------------------------- ### Use cross-env-shell for multi-command scripts Source: https://github.com/kentcdodds/cross-env/blob/main/README.md Use `cross-env-shell` when an environment variable needs to apply to several commands in series. Wrap the commands in quotes. ```json { "scripts": { "greet": "cross-env-shell GREETING=Hi NAME=Joe \"echo $GREETING && echo $NAME\"" } } ``` -------------------------------- ### isWindows() Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/OVERVIEW.md Detects if the current platform is Windows. ```APIDOC ## isWindows() ### Description Detect Windows platform. ### Returns - **boolean** - True if the current platform is Windows, false otherwise. ``` -------------------------------- ### Set Empty Environment Variable Values with cross-env Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md Demonstrates setting an environment variable to an empty string, either by providing no value or by using empty quotes. ```typescript crossEnv(['EMPTY=', 'node', 'app.js']) ``` ```typescript crossEnv(['EMPTY=\'\'', 'node', 'app.js']) ``` -------------------------------- ### Package.json Binaries Registration Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md This JSON configuration in package.json registers two CLI binaries for cross-env, which npm will make available in node_modules/.bin/. ```json { "bin": { "cross-env": "./dist/bin/cross-env.js", "cross-env-shell": "./dist/bin/cross-env-shell.js" } } ``` -------------------------------- ### Use cross-env via child_process.spawn Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md Integrate crossEnv with Node.js's built-in spawn function for more control over child process execution. This approach is recommended for most users. ```typescript import { spawn } from 'child_process' import { crossEnv } from 'cross-env' // But crossEnv itself uses cross-spawn internally // This is the recommended approach for most users const result = crossEnv(['NODE_ENV=test', 'npm', 'run', 'test']) ``` -------------------------------- ### Run Node.js script with environment variable Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/OVERVIEW.md Use this command to set environment variables for Node.js scripts in a cross-platform compatible way. It ensures that `NODE_ENV=production` is correctly interpreted on various operating systems. ```bash cross-env NODE_ENV=production node ./start.js ``` -------------------------------- ### Cross-env Options Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/SUMMARY.txt Configuration options for cross-env, such as enabling shell execution. ```typescript CrossEnvOptions ``` -------------------------------- ### Zshy Build Configuration Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md This JSON configuration specifies the build settings for the package using zshy, including disabling CommonJS output and defining export paths. ```json { "zshy": { "cjs": false, "exports": { ".": "./src/index.ts", "./bin/cross-env": "./src/bin/cross-env.ts", "./bin/cross-env-shell": "./src/bin/cross-env-shell.ts" } } } ``` -------------------------------- ### commandConvert Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/README.md Converts command syntax for the current platform, handling variable transformations. ```APIDOC ## commandConvert ### Description Converts command syntax for the current platform. On Windows, it transforms `$VAR` to `%VAR%`. It also handles bash parameter expansion defaults and can optionally normalize paths. ### Signature ```typescript commandConvert(command: string, env: NodeJS.ProcessEnv, normalize?: boolean): string ``` ### Parameters - **command** (string) - The command string to convert. - **env** (NodeJS.ProcessEnv) - The current environment variables. - **normalize** (boolean, optional) - Whether to normalize paths. ### Return Value - **string** - The converted command string. ### Example ```javascript import { commandConvert } from 'cross-env'; const env = { ...process.env }; const convertedCommand = commandConvert('echo $USER', env); console.log(convertedCommand); // Output might be 'echo %USER%' on Windows ``` ``` -------------------------------- ### Environment Variable Composition Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md Construct environment variables using shell parameter expansion, providing default values if variables are not set. ```bash cross-env API_URL='http://'${API_HOST:-localhost}':'${API_PORT:-3000}' node app.js ``` -------------------------------- ### Pass JSON String as Environment Variable Source: https://github.com/kentcdodds/cross-env/blob/main/README.md Demonstrates how to pass a JSON string as an environment variable, which is common when configuring tools like ts-loader. Pay close attention to the escaping of quotes and backslashes for cross-platform compatibility. ```json { "scripts": { "test": "cross-env TS_NODE_COMPILER_OPTIONS={\"module\":\"commonjs\"} node some_file.test.ts" } } ``` -------------------------------- ### Windows: Simple Variable Reference Conversion Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/command-convert.md On Windows, simple variable references like $VARNAME are converted to the Windows format %VARNAME%. ```typescript commandConvert('echo $HOME', { HOME: 'C:\\Users\\John' }) // On Windows: 'echo %HOME%' // On Unix: 'echo $HOME' ``` -------------------------------- ### Use Shell Option with cross-env Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md Enable shell features like piping and command chaining by setting the `shell` option to `true`. ```typescript crossEnv( ['NODE_ENV=test', 'npm run build && npm test'], { shell: true } ) ``` -------------------------------- ### commandConvert Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/INDEX.md Converts a given command string into a platform-specific command string, optionally normalizing it. ```APIDOC ## commandConvert ### Description Converts a command string to a platform-specific format, with an option for normalization. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature `commandConvert(command: string, env: NodeJS.ProcessEnv, normalize?: boolean): string` ### Parameters - **command** (string) - Required - The command string to convert. - **env** (NodeJS.ProcessEnv) - Required - The current environment variables. - **normalize** (boolean) - Optional - Whether to normalize the command. ### Return Value - **string** - The converted command string. ### Reference [[api-reference/command-convert]] ``` -------------------------------- ### Handling Empty Variables Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/errors.md Demonstrates how cross-env handles referenced empty variables by replacing them with an empty string in the command execution. ```typescript crossEnv(['EMPTY=', 'echo', '$EMPTY', 'test']) ``` -------------------------------- ### Variable Reference Resolution Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/api-reference/var-value-convert.md Shows how environment variable references, using both $VARNAME and ${VARNAME} syntax, are resolved to their actual values from process.env. If a variable is not found, it's replaced with an empty string. ```typescript process.env.BASE = 'localhost' varValueConvert('http://$BASE:3000', 'API_URL') // 'http://localhost:3000' varValueConvert('http://${BASE}:3000', 'API_URL') // 'http://localhost:3000' ``` -------------------------------- ### Execute Commands without Shell Interpretation (CLI) Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/ENTRY_POINTS.md Use the `cross-env` CLI binary to execute commands directly without involving the system shell. This is useful for avoiding shell-specific syntax or behavior. ```bash cross-env NODE_ENV=production npm run build ``` ```typescript import { crossEnv } from '../index.js' crossEnv(process.argv.slice(2)) ``` -------------------------------- ### commandConvert() Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/SUMMARY.txt A utility function that converts a command string to its platform-specific equivalent, handling differences between Windows and Unix-like systems. ```APIDOC ## commandConvert() ### Description Converts a given command string into its platform-specific representation, accounting for differences in command syntax and execution between Windows and Unix-like environments. ### Method `commandConvert(command: string): string` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import { commandConvert } from 'cross-env'; const unixCommand = 'echo "Hello World"'; const windowsCommand = commandConvert(unixCommand); console.log(windowsCommand); // Example output: echo "Hello World" ``` ### Response #### Success Response - **convertedCommand** (string) - The platform-specific command string. #### Response Example ```json { "convertedCommand": "echo \"Hello World\"" } ``` ``` -------------------------------- ### Combining with npm Scripts Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md Integrate cross-env into npm scripts for setting environment variables during build, development, or production runs. ```json { "scripts": { "dev": "cross-env NODE_ENV=development node server.js", "start": "npm run build && npm run dev", "build": "cross-env NODE_ENV=production webpack" } } ``` -------------------------------- ### API Endpoint Override Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/EXAMPLES.md Override the base URL for API requests during testing to point to a staging environment. ```bash cross-env API_BASE_URL=https://staging.example.com npm run test ``` -------------------------------- ### CLI: Shell Execution Source: https://github.com/kentcdodds/cross-env/blob/main/_autodocs/SUMMARY.txt A cross-env CLI binary specifically designed for executing commands within a shell environment, useful for complex commands or shell-specific features. ```bash #!/usr/bin/env node // bin/cross-env-shell.ts require('../index.js') ```