Constantinople is a JavaScript utility package, currently at stable version 4.0.1, designed to determine if a given JavaScript expression evaluates to a constant. It parses the expression into an Abstract Syntax Tree (AST) using Babylon (now part of Babel's parser) to analyze its predictability. The library prioritizes safety, conservatively returning `false` if there's any uncertainty, ensuring reliability for build tools and static analysis where incorrect constant detection could cause issues. It also provides a `toConstant` function to safely evaluate expressions identified as constant, throwing an error if the expression is not constant. The package ships with TypeScript type definitions, enhancing developer experience for TypeScript users.
npm install constantinopleVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to use `isConstant` to check if an expression is constant and `toConstant` to evaluate its value, including handling non-constant expressions and custom constant contexts.
Carefully curate the `constants` object, ensuring it only contains truly static values or functions without side effects. Avoid passing global objects that include non-constant methods if the expression might call them.
Always wrap calls to `isConstant.toConstant()` in a `try...catch` block, or, preferably, ensure you call `isConstant()` first and only invoke `toConstant()` if `isConstant()` returns `true`.
If differentiating between non-constant and syntax errors is crucial, consider pre-validating syntax with a linter or a dedicated parser, or rely on `toConstant`'s error throwing behavior for invalid syntax when precise error types are needed.
Ensure `isConstant()` returns `true` for an expression before calling `isConstant.toConstant()`, or wrap `isConstant.toConstant()` calls in a `try...catch` block to handle this expected error.
Review and correct the syntax of the input expression string. `isConstant()` will return `false` for syntax errors, while `isConstant.toConstant()` will throw a `SyntaxError`.
Import `isConstant` as a default export (`import isConstant from 'constantinople';`) and access `toConstant` as a property of the imported object (`isConstant.toConstant`). For CommonJS, use `const isConstant = require('constantinople');`.No dependency data recorded yet.