Babel plugin that validates ES2015 const declarations by preventing reassignment at compile time
npx @tessl/cli install tessl/npm-babel-plugin-check-es2015-constants@6.22.0A Babel plugin that validates ES2015 const declarations by preventing reassignment of const variables at compile time. It provides early detection of const violations during the compilation process rather than at runtime.
npm install --save-dev babel-plugin-check-es2015-constantsThis is a Babel plugin, so it's typically used via Babel configuration rather than direct imports:
.babelrc:
{
"plugins": ["check-es2015-constants"]
}Via Node API:
const babel = require("babel-core");
const result = babel.transform(code, {
plugins: ["check-es2015-constants"]
});Via CLI:
babel --plugins check-es2015-constants script.jsThe plugin automatically validates const declarations during compilation. No additional configuration is required.
// Input code
const a = 1;
a = 2; // This will throw a compile-time error
// Error output:
// SyntaxError: "a" is read-onlyComplex const validation:
// The plugin catches various forms of const violations
const obj = { prop: 1 };
obj = {}; // Error: "obj" is read-only
const [x, y] = [1, 2];
x = 3; // Error: "x" is read-only
// But property mutations are allowed (this is valid)
const obj2 = { prop: 1 };
obj2.prop = 2; // OK - not reassigning the const bindingThe plugin follows the standard Babel plugin architecture:
The main plugin factory function that creates the Babel plugin.
/**
* Default export - Creates a Babel plugin for checking ES2015 const violations
* @param {Object} context - Babel plugin context containing messages
* @param {Object} context.messages - Babel messages object for error formatting
* @returns {Object} Babel plugin object with visitor methods
*/
export default function ({ messages }) {
return {
visitor: {
Scope({ scope }) { /* implementation */ }
}
};
}The plugin object returned by the factory function.
interface BabelPlugin {
/** AST visitor methods for traversing code */
visitor: {
/** Processes each scope to check for const violations */
Scope(path: { scope: Scope }): void;
};
}Processes each scope in the AST to validate const declarations.
/**
* Scope visitor that checks for const binding violations
* @param {Object} path - Babel path object
* @param {Scope} path.scope - Babel scope containing bindings information
* @throws {Error} Throws compile-time error for const violations
*/
function Scope({ scope }) {
// Iterates through bindings and throws errors for const violations
}The plugin throws compile-time errors when const violations are detected:
buildCodeFrameError"<variable_name>" is read-onlyExample error output:
repl: "a" is read-only
1 | const a = 1;
> 2 | a = 2;
| ^The plugin validates the following binding types:
constViolation types detected:
const a = 1; a = 2;)const a = 1; a++;)const a = 1; a += 1;)transform-es2015-block-scoping for full ES2015 const support