使用Chart.js v3.0与chartjs-plugin-annotation v1.4.0时出现编译错误
addRoundedRectPath导出错误 问题场景
在Angular 14项目中使用Chart.js,组件中导入并注册代码如下:
import { Chart, registerables } from 'chart.js'; import 'chartjs-plugin-annotation'; Chart.register(...registerables);
出现编译错误:
./node_modules/chartjs-plugin-annotation/dist/chartjs-plugin-annotation.esm.js:438:2-20 - Error: export 'addRoundedRectPath' (imported as 'addRoundedRectPath') was not found in 'chart.js/helpers' (possible exports: HALF_PI, INFINITY, PI, PITAU, QUARTER_PI, RAD_PER_DEG, TAU, TWO_THIRDS_PI, _addGrace, _alignPixel, _alignStartEnd, _angleBetween, _angleDiff, _arrayUnique, _attachContext, _bezierCurveTo, _bezierInterpolation, _boundSegment, _boundSegments, _capitalize, _computeSegments, _createResolver, _decimalPlaces, _deprecated, _descriptors, _elementsEqual, _factorize, _filterBetween, _getParentNode, _int16Range, _isPointInArea, _limitValue, _longestText, _lookup, _lookupByKey, _measureText, _merger, _mergerIf, _normalizeAngle, _pointInLine, _rlookupByKey, _setMinAndMaxByKey, _steppedInterpolation, _steppedLineTo, _textX, _toLeftRightCenter, _updateBezierControlPoints, almostEquals, almostWhole, callback, clearCanvas, clipArea, clone, color, debounce, defined, distanceBetweenPoints, drawPoint, each, easingEffects, finiteOrDefault, fontString, formatNumber, getAngleFromPoint, getHoverColor, getMaximumSize, getRelativePosition, getRtlAdapter, getStyle, isArray, isFinite, isFunction, isNullOrUndef, isNumber, isObject, listenArrayEvents, log10, merge, mergeIf, niceNum, noop, overrideTextDirection, readUsedSize, renderText, requestAnimFrame, resolve, resolveObjectKey, restoreTextDirection, retinaScale, sign, splineCurve, splineCurveMonotone, supportsEventListenerOptions, throttled, toDegrees, toDimension, toFont, toFontString, toLineHeight, toPadding, toPercentage, toRadians, toTRBL, toTRBLCorners, uid, unclipArea, unlistenArrayEvents, valueOrDefault)
根据插件文档说明,Chart.js 3.0.0至3.6.2需使用插件1.4.0版本,但仍出现该错误。
解决方案
1. 明确版本匹配规则
错误根源是chartjs-plugin-annotation版本与Chart.js版本不兼容:
- 插件v1.4.0:仅支持Chart.js 3.0.0 ~ 3.6.2
- 插件v2.x及以上:要求Chart.js ≥3.7.0(依赖Chart.js 3.7.0新增的
addRoundedRectPath方法)
2. 检查当前安装版本
运行命令查看已安装的版本:
npm list chart.js chartjs-plugin-annotation
3. 根据Chart.js版本调整插件版本
如果Chart.js版本 ≤3.6.2:
强制安装插件1.4.0版本:npm install chartjs-plugin-annotation@1.4.0 --save如果Chart.js版本 ≥3.7.0:
升级插件到兼容的最新版本:npm install chartjs-plugin-annotation@latest --save
4. 修正插件注册方式
确保将annotation插件也注册到Chart实例中,避免后续运行时错误:
import { Chart, registerables } from 'chart.js'; import annotationPlugin from 'chartjs-plugin-annotation'; // 同时注册核心组件和插件 Chart.register(...registerables, annotationPlugin);
内容的提问来源于stack exchange,提问作者Rich Stewart

