使用原生JS结合Chart.js时出现'Uncaught ReferenceError: Chart is not defined'错误求助
解决Chart.js 4.x版本出现'Uncaught ReferenceError: Chart is not defined'的问题
你遇到的错误核心原因是Chart.js 4.x版本的UMD模块加载逻辑和2.x不同,导致全局Chart变量未被正确暴露。下面是两种可行的解决方法:
方法一:移除模块类型声明(推荐,适配原有代码结构)
Chart.js的chart.umd.js是UMD格式脚本,默认会把Chart挂载到全局作用域。但你给script标签加了type="module",会让脚本在模块作用域内运行,不会暴露全局变量,导致后续普通脚本无法访问Chart。
只需要修改引入脚本的标签,去掉type="module":
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.3.2/chart.umd.js"></script>
同时可以把代码里的this.getRandomInt改为直接调用getRandomInt(全局函数无需通过this访问),修改后的完整代码如下:
<!DOCTYPE html> <html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.3.2/chart.umd.js"></script> </head> <body> <canvas id="myChart" style="max-height:400px; max-width:500px"></canvas> <script type="text/javascript"> function getRandomInt(n, min, max) { let result = new Array(); for (let i=0;i<n;i++) { min = Math.ceil(min); max = Math.floor(max); result.push(Math.floor(Math.random() * (max - min) + min)); } return result; } var myChart = document.getElementById('myChart'); const labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul']; const data = { labels: labels, datasets: [ { label: 'Dataset 1', data: getRandomInt(7, -100, 100), borderColor: '#f22613', }, { label: 'Dataset 2', data: getRandomInt(7, -100, 100), borderColor: '#4287f5', } ] }; const config = { type: 'line', data: data, options: { responsive: true, plugins: { legend: { position: 'top', }, }, }, }; new Chart(myChart, config); </script> </body> </html>
方法二:使用ES模块导入(适合现代项目的模块开发模式)
如果想保留type="module",需要把后续的脚本也改为模块类型,并显式导入Chart对象:
- 保持引入脚本的
type="module" - 将业务代码的script标签也改为
type="module" - 添加导入语句获取
Chart
修改后的代码示例:
<!DOCTYPE html> <html> <head> <script type="module" src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.3.2/chart.umd.js"></script> </head> <body> <canvas id="myChart" style="max-height:400px; max-width:500px"></canvas> <script type="module"> import Chart from 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.3.2/chart.umd.js'; function getRandomInt(n, min, max) { let result = new Array(); for (let i=0;i<n;i++) { min = Math.ceil(min); max = Math.floor(max); result.push(Math.floor(Math.random() * (max - min) + min)); } return result; } var myChart = document.getElementById('myChart'); const labels = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul']; const data = { labels: labels, datasets: [ { label: 'Dataset 1', data: getRandomInt(7, -100, 100), borderColor: '#f22613', }, { label: 'Dataset 2', data: getRandomInt(7, -100, 100), borderColor: '#4287f5', } ] }; const config = { type: 'line', data: data, options: { responsive: true, plugins: { legend: { position: 'top', }, }, }, }; new Chart(myChart, config); </script> </body> </html>
为什么2.x版本能正常运行?
Chart.js 2.x的UMD脚本即使在模块模式下,也会强制把Chart挂载到全局作用域,而4.x版本遵循了更严格的模块规范,不再自动暴露全局变量,因此出现了兼容性差异。
内容的提问来源于stack exchange,提问作者Ricardo Schroeder
相关产品推荐
相关产品推荐

