Blazor WebAssembly中ChartJsBlazor.Fork报错:找不到ChartJsInterop.setupChart
问题解决:ChartJsBlazor.Fork 2.0.2 交互脚本为空导致
ChartJsInterop未定义 问题重现
运行Blazor WebAssembly项目时触发以下错误:
blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100] Unhandled exception rendering component: Could not find 'ChartJsInterop.setupChart' ('ChartJsInterop' was undefined). Error: Could not find 'ChartJsInterop.setupChart' ('ChartJsInterop' was undefined).
已按官方快速开始配置index.html资源引入:
<body> <div id="app">...</div> <div id="blazor-error-ui">...</div> <script src="_framework/blazor.webassembly.js"></script> <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script> <script src="_content/ChartJs.Blazor.Fork/ChartJsBlazorInterop.js"></script> </body>
通过浏览器开发者工具确认ChartJsBlazorInterop.js已加载但内容为空,调整引用顺序无效,Razor页面代码完全匹配官方饼图示例。
解决方案
1. 修复NuGet包资源问题
- 卸载并重新安装ChartJs.Blazor.Fork包,确保资源完整:
dotnet remove package ChartJs.Blazor.Fork dotnet nuget locals all --clear dotnet add package ChartJs.Blazor.Fork --version 2.0.2 - 安装完成后,检查项目依赖项中该包的
wwwroot目录是否包含非空的ChartJsBlazorInterop.js文件。
2. 手动添加交互脚本
若NuGet包本身存在资源缺失问题,直接手动添加脚本:
- 在项目
wwwroot目录下新建js文件夹,创建ChartJsBlazorInterop.js文件,写入核心交互代码:window.ChartJsInterop = { setupChart: function (canvasId, config) { const ctx = document.getElementById(canvasId).getContext('2d'); return new Chart(ctx, config); }, updateChart: function (canvasId, config) { const chart = Chart.getChart(canvasId); if (chart) { chart.data = config.data; chart.options = config.options; chart.update(); } }, destroyChart: function (canvasId) { const chart = Chart.getChart(canvasId); if (chart) chart.destroy(); } }; - 修改
index.html中的脚本引用路径:<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script> <script src="js/ChartJsBlazorInterop.js"></script>
3. 确认资源加载顺序
确保脚本加载顺序为:Chart.min.js → 交互脚本 → blazor.webassembly.js,保证Chart.js和交互脚本在Blazor初始化前完成加载。
内容的提问来源于stack exchange,提问作者Matias Hansen
相关产品推荐
相关产品推荐

