babel-plugin-jsdoc-to-assert
raw JSON →A Babel plugin that converts JSDoc type annotations (@param and @type) into runtime assertion statements (console.assert) for testing. Version 4.0.0 is the current stable release, requiring Babel 7+. The plugin transforms static type documentation into executable checks, enabling runtime verification without a separate type system. Unlike TypeScript or Flow, it operates at the AST level during Babel transpilation and supports generic arrays (e.g., number[]) and rest parameters. Its primary differentiator is seamless integration into Babel workflows for development-only assertions, with options to enable/disable @param and @type checking. The package is maintained by azu and has a preset version (babel-preset-jsdoc-to-assert). Releases are infrequent, focusing on compatibility and bug fixes.
Common errors
error ERROR in ./src/js/framework/Context.js Module build failed: SyntaxError: Unterminated string constant (3:16) ↓
error AssertionError: Invalid JSDoc: typeof _this === 'string' ↓
error ReferenceError: console is not defined ↓
Warnings
breaking v4.0.0 drops Babel 6 support; requires Babel 7 or later. ↓
gotcha checkAtType is disabled by default because ES2015 transforms may run before this plugin, causing AssertionError with incorrect variable names (e.g., typeof _this === 'string'). ↓
gotcha Plugin uses console.assert, which does not throw on failure in Node.js (only prints to stderr). For test frameworks, use babel-preset-jsdoc-to-assert with useSpecReporter. ↓
deprecated v3.x and earlier used jsdoc-to-assert internally; v4.0.0 may have updated dependencies. ↓
gotcha The plugin may fail on files with syntax errors (e.g., unterminated string constants). Reported as SyntaxError during babel build. ↓
Install
npm install babel-plugin-jsdoc-to-assert yarn add babel-plugin-jsdoc-to-assert pnpm add babel-plugin-jsdoc-to-assert Imports
- default wrong
import plugin from 'babel-plugin-jsdoc-to-assert'correctmodule.exports = require('babel-plugin-jsdoc-to-assert') - jsdoc-to-assert plugin name wrong
"plugins": ["babel-plugin-jsdoc-to-assert"]correct"plugins": ["jsdoc-to-assert"] - options wrong
"plugins": ["jsdoc-to-assert", { "checkAtType": true }]correct"plugins": [["jsdoc-to-assert", { "checkAtType": true }]]
Quickstart
// .babelrc
{
"plugins": ["jsdoc-to-assert"],
"env": {
"development": {
"plugins": ["jsdoc-to-assert"]
}
}
}
// Source file (src/index.js)
/**
* Adds two numbers.
* @param {number} a - first number
* @param {number} b - second number
* @returns {number} sum
*/
function add(a, b) {
return a + b;
}
// Build script (package.json)
"scripts": {
"build": "NODE_ENV=production babel src --out-dir lib --source-maps"
}
// After transform (development build): function add(a, b) { console.assert(typeof a === 'number'); console.assert(typeof b === 'number'); return a + b; }