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

使用SortableJS实现拖拽功能时遇模块解析错误求助

解决SortableJS模块解析错误:Failed to resolve module specifier "sortablejs"

问题原因

浏览器原生ES模块不支持直接导入npm包名,必须使用相对路径、绝对路径或完整的CDN URL。你代码里的import Sortable from "sortablejs"用了包名,导致模块解析失败。

可行解决方案

方案1:使用CDN的ES模块版本

直接替换import语句为CDN提供的ES模块地址:

/*===== DRAG and DROP =====*/
import Sortable from 'https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.esm.js';

const dropItems = document.getElementById('drop-items')

new Sortable(dropItems, {
    animation: 350,
    chosenClass: "sortable-chosen",
    dragClass: "sortable-drag"
});

同时要确保HTML中的script标签添加type="module"属性:

<script type="module" src="你的JS文件路径"></script>

方案2:通过npm安装+打包工具构建

  1. 先安装SortableJS:
npm install sortablejs
  1. 使用Vite、Webpack等打包工具处理项目,这类工具会自动解析import Sortable from "sortablejs",生成浏览器可识别的代码。

方案3:下载本地文件并使用相对路径

  1. 从SortableJS官方仓库下载ES模块版本文件(Sortable.esm.js)
  2. 将文件放到你的项目目录中(比如和当前JS文件同目录)
  3. 修改import语句为相对路径:
import Sortable from './Sortable.esm.js';

内容的提问来源于stack exchange,提问作者Hameed Ayoola

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 07:20:36