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

使用Hyphenopoly出现Uncaught TypeError错误的求助

问题

尝试使用Hyphenopoly控制指定区块(messages_container)的文本换行时,触发以下错误:

Uncaught TypeError: Cannot convert undefined or null to object
at Function.entries (<anonymous>)
at Hyphenopoly.js:153:11
at Hyphenopoly.js:209:7
at Hyphenopoly.js:933:3

我的实现代码如下:

document.addEventListener('DOMContentLoaded', function() {
  
  Hyphenopoly.addPattern('en', {
   
    "async": true,
    "path": *my link*
  });
  Hyphenopoly.config({

  }).then(() => {

    const messagesContainer = document.getElementById('messages_container'); 
    const text = messagesContainer ? messagesContainer.innerText : ''; 
    console.log(text);
    const hyphenatedText = Hyphenopoly.hyphenateText(text);
    console.log(hyphenatedText);
  }).catch((error) => {
    console.error(error);
  });
});

已确认链接及相关文件无异常,需解决该错误以实现文本换行控制。

解决方案
  • 禁止传入空config对象:Hyphenopoly.config()必须包含基础配置(至少指定需要启用连字符的语言),空对象会导致内部处理Object.entries时触发类型错误。建议将模式配置整合到config中,示例如下:
    document.addEventListener('DOMContentLoaded', function() {
      Hyphenopoly.config({
        "require": ["en"], // 指定需要加载的语言
        "patterns": {
          "en": {
            "async": true,
            "path": "你的模式文件目录路径" // 替换为实际路径,比如"/hyphenopoly/patterns/"
          }
        }
      }).then((Hyphenator) => {
        const messagesContainer = document.getElementById('messages_container'); 
        const text = messagesContainer ? messagesContainer.innerText : ''; 
        const hyphenatedText = Hyphenator.hyphenateText(text); // 使用返回的实例调用方法
        console.log(hyphenatedText);
      }).catch((error) => {
        console.error(error);
      });
    });
    
  • 使用config返回的实例调用方法:Hyphenopoly.config()的then回调会返回初始化完成的Hyphenator实例,必须用这个实例调用hyphenateText,而非直接使用全局Hyphenopoly对象,否则可能在初始化未完成时触发错误。
  • 统一管理模式配置:不要单独调用addPattern,将语言模式配置放到config的patterns属性中,确保初始化流程正确衔接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 19:53:29