
本文详解为何 import * as he from 'he' 后调用 he.decode() 报错“not a function”,并提供完整解决方案:必须安装运行时库 he(而非仅类型定义 @types/he),同时给出正确的导入方式与使用示例。
本文详解为何 `import * as he from 'he'` 后调用 `he.decode()` 报错“not a function”,并提供完整解决方案:必须安装运行时库 `he`(而非仅类型定义 `@types/he`),同时给出正确的导入方式与使用示例。
在 TypeScript 项目中,开发者常误将类型定义包(如 @types/he)当作功能库本身安装,导致代码编译通过但运行时报错 TypeError: he.decode is not a function。根本原因在于:@types/he 仅提供类型声明,不包含任何可执行逻辑;真正实现 decode()、encode() 等功能的是 he 这个 JavaScript 库。
✅ 正确安装步骤如下:
# 卸载错误的依赖(如果已安装) npm uninstall @types/he # 安装真正的 he 库(含运行时代码 + 自带类型定义) npm install he
✅ 注意:自 v1.2.0 起,he 官方包已内置 TypeScript 类型声明(index.d.ts),无需额外安装 @types/he。重复安装反而可能导致类型冲突或模块解析异常。
✅ 正确导入与使用方式(推荐 ES 模块语法):
// 方式 1:默认导入(推荐,语义清晰且 Tree-shaking 友好) import he from 'he'; const animal_stuff = '<div>Café & Co.</div>'; console.log(he.decode(animal_stuff)); // 输出:"<div>Café & Co.</div>"
// 方式 2:命名导入(如需按需使用特定函数)
import { decode, encode } from 'he';
console.log(decode('"Hello"')); // 输出:'"Hello"'
console.log(encode('<script>alert(1)</script>')); // 输出:'<script>alert(1)</script>'
⚠️ 常见误区提醒:
- ❌ import * as he from 'he' 在部分构建工具(如 Vite、Webpack 5+)中可能因模块格式不匹配导致 he 成为一个空对象,进而 he.decode 为 undefined;
- ✅ 优先使用默认导入(import he from 'he')或具名导入(import { decode } from 'he'),二者均经官方验证兼容性最佳;
- 若使用 CommonJS 环境(如 Node.js
总结:解决 he.decode is not a function 的核心是——安装 he 本体,而非仅其类型包。安装后选择语义明确、工具链友好的导入方式,并确保构建配置支持 ES 模块解析,即可稳定调用全部 HTML 实体编解码能力。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











