You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Spring Boot(Thymeleaf)中使用JS import引入chart.js的问题

解决Spring Boot + Thymeleaf中使用Chart.js模块导入的问题

核心问题原因

  • 未添加type="module"时,浏览器将脚本视为传统非模块脚本,不支持import语法,因此抛出Cannot use import statement outside a module错误。
  • 添加type="module"后,浏览器要求模块路径必须是相对路径(./、../)、绝对路径(/开头)或完整URL,无法直接识别chart.js/auto这类npm包名,所以出现Failed to resolve module specifier错误。

解决方案1:使用CDN导入(最适合新手快速解决)

直接在独立脚本文件中通过CDN完整URL导入Chart.js,无需依赖本地node_modules:

  1. 在HTML中引入你的脚本(保持type="module"):
<script type="module" th:src="@{/js/graficaLoader.js}"></script>
  1. 在graficaLoader.js中用CDN路径导入Chart.js:
// 使用Chart.js官方CDN的ES模块版本
import Chart from 'https://cdn.jsdelivr.net/npm/chart.js/auto/dist/chart.esm.js';

// 示例:初始化图表
const ctx = document.getElementById('myChart').getContext('2d');
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Red', 'Blue', 'Yellow'],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3],
            backgroundColor: ['rgba(255, 99, 132, 0.2)'],
            borderColor: ['rgba(255, 99, 132, 1)'],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            y: { beginAtZero: true }
        }
    }
});

解决方案2:手动复制本地Chart.js文件到静态资源

如果你不想用CDN,可以从node_modules中提取编译好的模块文件,放到Spring Boot静态资源目录:

  1. 找到本地node_modules/chart.js/auto/dist/chart.esm.js文件,复制到Spring Boot的src/main/resources/static/js/lib/目录下(无lib文件夹则新建)。

  2. 在graficaLoader.js中用相对路径导入:

// 根据目录结构调整路径,此处假设graficaLoader.js在js目录,lib是js的子目录
import Chart from './lib/chart.esm.js';

// 后续图表初始化代码同上
  1. HTML中的脚本引入和方案1一致,保持type="module"。

解决方案3:使用前端构建工具打包(适合复杂项目)

如果前端代码较多,建议用Vite、Webpack这类工具打包:

  • 初始化前端项目,安装Chart.js依赖。
  • 编写模块代码,通过构建工具打包成单个兼容浏览器的脚本文件。
  • 将打包后的文件放到Spring Boot静态资源目录,直接用普通<script>标签引入即可(无需type="module")。

内容的提问来源于stack exchange,提问作者Felix Caba

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 23:12:07