如何为导出函数的JavaScript模块创建TypeScript声明文件?
CommonJS 单函数导出模块的 TypeScript 声明编写指南
问题场景
需要为一个采用CommonJS规范导出纯函数的JavaScript模块编写TypeScript声明文件,对应的模块源码为:
module.exports = hello function hello() { console.log('Hello') }
已尝试的三类声明写法均无法适配业务侧的两种导入方式:
尝试过的错误声明:
- 纯ES命名导出写法
export function hello(): void - 纯ES默认导出写法
export default function hello(): void - 无兼容属性的CommonJS导出写法
declare function hello(): void export = hello
无法正常生效的导入写法:
- 默认导入语法:
import hello from './filename' - 命名导入语法:
import { hello } from './filename'
问题根源
失效的核心原因是CommonJS和ES模块的导出、导入映射规则不匹配,和TypeScript对两类模块的兼容逻辑相关:
- 纯ES模块的导出写法(
export function/export default)和JS实际通过module.exports在根对象挂载值的CommonJS逻辑不匹配,运行时会出现导出值为undefined的错位 - 裸
export = hello的写法虽然和CommonJS的导出逻辑完全对齐,但没有在导出的对象上挂载hello同名属性,因此TypeScript会直接判定import { hello }的命名导入不存在对应导出项 - 若未开启
tsconfig.json中的esModuleInterop配置,纯export =的写法甚至无法支持ES风格的import xxx from语法,必须强制使用CommonJS的import xxx = require()导入形式
正确实现方案
前置配置
确保项目tsconfig.json中开启 esModuleInterop: true(为TypeScript新项目默认推荐配置,可自动完成CommonJS和ES模块的语法兼容垫片)。
对应的声明文件写法
针对该CommonJS模块,编写对应.d.ts声明文件如下,可同时兼容两种导入语法:
declare function hello(): void // 给导出的函数对象挂载同名属性,适配命名导入逻辑 declare namespace hello { export { hello } } export = hello
生效逻辑
完成上述声明后,两类导入语法均可正常工作,拿到的是同一个函数实例:
- 使用
import hello from './filename'时,直接拿到根导出的函数本身 - 使用
import { hello } from './filename'时,读取到挂载在函数对象上的同名属性,和前者完全等价
如果项目未开启
esModuleInterop配置,需要补充手动兼容的默认导出属性,声明写法调整为:declare function hello(): void declare namespace hello { export const hello: typeof hello export default hello } export = hello
内容的提问来源于stack exchange,提问作者user311413
相关产品推荐
相关产品推荐

