You need to enable JavaScript to run this app. 引入jspdf运行时报Cannot use import statement outside a module如何解决
优惠活动
大模型
产品
解决方案
定价
更多

引入jspdf运行时报Cannot use import statement outside a module如何解决

错误原因

普通script标签默认不属于ES模块环境,不支持import语法;且你引入的是UMD格式的jsPDF资源,会直接挂载全局对象,不需要也不能用import导入。

解决方案

下面给出两种可直接运行的修复方案:

方案1:使用UMD全局对象(兼容性最优)

直接删除import语句,调用UMD格式自动挂载到window上的jspdf对象即可,修改后完整代码如下:

<!DOCTYPE html>
<html>
<head>
    <title>Test 2</title>
    <script src="https://unpkg.com/jspdf@latest/dist/jspdf.umd.min.js"></script>
    <script type="text/javascript">
        const { jsPDF } = window.jspdf;

        // Default export is a4 paper, portrait, using millimeters for units
        const doc = new jsPDF();

        doc.text("Hello world!", 10, 10);
        doc.save("a4.pdf");
        alert("hello")
    </script>
</head>
<body>
</body>
</html>

方案2:使用ES模块写法

如果需要保留import语法,将script标签的type改为module,同时导入ES模块版本的jsPDF资源即可:

<!DOCTYPE html>
<html>
<head>
    <title>Test 2</title>
    <script type="module">
        import { jsPDF } from "https://unpkg.com/jspdf@latest/dist/jspdf.es.min.js";

        // Default export is a4 paper, portrait, using millimeters for units
        const doc = new jsPDF();

        doc.text("Hello world!", 10, 10);
        doc.save("a4.pdf");
        alert("hello")
    </script>
</head>
<body>
</body>
</html>

内容的提问来源于stack exchange,提问作者Geordi tyrrell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 03:24:03