如何在Rails 7中正确导入tesseract.js?
Rails 7 中正确导入 tesseract.js 的方法
问题描述
我在新的 Rails 7 项目中尝试导入 JavaScript 库 tesseract.js,已通过 yarn 完成依赖安装:
yarn add tesseract.js
我的 package.json 文件内容如下:
{ "dependencies": { "tesseract.js": "^3.0.3" } }
application.js 文件配置如下:
import "@hotwired/turbo-rails" import "controllers" import "tesseract.js"
但测试用的 JS 文件无法识别相关代码,测试代码如下:
const player = document.getElementById('player'); const snapshotZone = document.getElementById('snapshot'); const captureButton = document.getElementById('capture'); const result = document.getElementById('result'); navigator.mediaDevices.getUserMedia({ video: true }).then(stream => { player.srcObject = stream }) captureButton.addEventListener('click', function() { const context = snapshot.getContext('2d') context.drawImage(player, 0, 0, snapshotZone.width, snapshotZone.height) Tesseract.recognize(snapshotZone, 'eng', { logger: m => console.log(m) }) // 英文 .then(({ data: { text } }) => { result.value = text }) })
这段代码在 Codepen 中可正常运行,请问如何正确导入 tesseract.js?
解决方法
1. 显式导入 Tesseract 对象
Rails 7 使用 ES 模块规范,直接 import "tesseract.js" 不会自动将 Tesseract 挂载到全局 window 对象。需要在测试代码所在的文件中显式导入:
import Tesseract from 'tesseract.js'; // 你的测试代码 const player = document.getElementById('player'); const snapshotZone = document.getElementById('snapshot'); const captureButton = document.getElementById('capture'); const result = document.getElementById('result'); navigator.mediaDevices.getUserMedia({ video: true }).then(stream => { player.srcObject = stream }) captureButton.addEventListener('click', function() { const context = snapshot.getContext('2d') context.drawImage(player, 0, 0, snapshotZone.width, snapshotZone.height) Tesseract.recognize(snapshotZone, 'eng', { logger: m => console.log(m) }) .then(({ data: { text } }) => { result.value = text }) })
2. 手动挂载到全局(适用于多文件复用场景)
如果需要在多个文件中直接使用全局的 Tesseract,可以修改 application.js,将其挂载到 window 对象:
import "@hotwired/turbo-rails" import "controllers" import Tesseract from "tesseract.js" window.Tesseract = Tesseract;
修改后,你的测试代码无需单独导入,直接调用 Tesseract.recognize 即可正常运行。
3. 确认代码加载顺序
确保测试代码在 application.js 之后加载,或者通过 Rails 的资源管道正确引入:
- 测试文件需放在
app/javascript目录下; - 若为独立文件,需在
application.js中导入,或在视图中通过javascript_importmap_tags确保加载顺序正确。
另外注意:你安装时的命令拼写有误(yarn add terresact.js),不过从 package.json 来看实际已正确安装 tesseract.js,此问题不影响功能。
内容的提问来源于 stack exchange,提问作者 Giordano Díaz
相关产品推荐
相关产品推荐

