使用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
相关产品推荐
相关产品推荐

