Electron主进程使用pdf.js遇模块兼容错误,求解决方案
解决Electron主进程中使用pdf.js的模块导入错误
1. 修正基础语法错误
你写的代码混合了ES模块的import和CommonJS的require语法,这本身就是错误的,正确写法二选一:
- CommonJS写法:
const { getDocument } = require('pdfjs-dist');
- ES模块写法:
import { getDocument } from 'pdfjs-dist';
2. 针对ES模块兼容问题的解决方案
pdf.js当前发布的包为ES模块格式,而Electron主进程默认是CommonJS环境,直接用require会触发你遇到的错误,以下是两种可行方案:
方案一:使用动态import(推荐,无需修改全局配置)
在CommonJS模块中,用动态import()加载ES模块,这是官方推荐的兼容方式:
async function loadPDF() { const { getDocument } = await import('pdfjs-dist'); // 调用getDocument处理PDF const pdfDoc = await getDocument({ url: '你的PDF文件路径' }).promise; // 后续PDF操作逻辑 } loadPDF();
方案二:将主进程改为ES模块环境
如果想全局使用ES模块,需要:
- 在项目根目录的
package.json中添加"type": "module" - 主进程入口文件后缀改为
.mjs,或保持.js但确保所有依赖模块均为ES模块格式 - 替换Electron主进程中CommonJS专属API,比如
__dirname:
import { fileURLToPath } from 'url'; import { dirname } from 'path'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename);
3. 你之前尝试操作的问题分析
nodeIntegration设为true:该参数控制渲染进程是否可访问Node.js API,和主进程的模块加载问题无关,因此无效- 使用
index.cjs:若pdf.js未提供完整的CommonJS格式入口,直接引用该文件会因内部依赖仍为ES模块而报错 - 修改
package.json的type为module后报错:大概率是主进程中仍保留require、__dirname等CommonJS语法,未替换为ES模块写法
内容的提问来源于stack exchange,提问作者Maxime B
相关产品推荐
相关产品推荐

