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

html-entities 2.3.3版本报错Entities不是构造函数如何解决?

修复html-entities 2.3.3版本的"Entities is not a constructor"错误

问题出在html-entities 2.x版本的导出结构和旧版本不同——你代码中通过require('html-entities').XmlEntities获取到的是已经实例化完成的对象,而非可new的构造函数,因此调用new Entities()会抛出类型错误。

以下是两种修复方案:

方案一:直接使用预实例化的对象(推荐,适合常规场景)

2.x版本默认导出了已配置好的实体处理实例,无需手动new,直接调用方法即可:

const { XmlEntities } = require('html-entities');

// 编码示例
const encodedStr = XmlEntities.encode('<div>Hello & World</div>');
// 解码示例
const decodedStr = XmlEntities.decode('&lt;div&gt;Hello &amp; World&lt;/div&gt;');

方案二:手动实例化构造函数(适合需要自定义配置的场景)

如果需要自定义实体映射、编码规则等高级操作,需要从模块内部路径导入构造函数:

const XmlEntities = require('html-entities/lib/xml-entities').XmlEntities;
const entities = new XmlEntities();

// 调用实例方法
const encodedStr = entities.encode('<div>Hello & World</div>');
const decodedStr = entities.decode('&lt;div&gt;Hello &amp; World&lt;/div&gt;');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:05:34