TSdx开发Jest Reporter npm包时报Class constructor无new调用错误的配置问题
TSdx开发Jest自定义Reporter的class继承报错解决方案
现象说明
基于TSdx开发适用于Jest的小型Reporter npm包时,包内自定义Reporter类继承Jest提供的BaseReporter基类,发布到项目中使用时会触发报错:
Uncaught TypeError: Class constructor BaseReporter cannot be invoked without 'new' at new ExampleReporter (..\dist\example-reporter.cjs.development.js:37:26)
报错可通过以下路径100%复现:
- 执行
npx tsdx watch --onSuccess node .启动构建监听 - 待Node REPL启动后,执行实例化代码
new (require('.').ExampleReporter)() - 直接触发同上述一致的构造器调用报错
核心实现代码为:
import BaseReporter from '@jest/reporters/build/base_reporter'; export class ExampleReporter extends BaseReporter { // 自定义Reporter逻辑实现 }
问题根因
该报错本质是构建产物的模块兼容层行为与原生ES class的语义冲突:
TSdx默认的CommonJS输出流程,会通过interopRequireDefault工具函数对所有ES Module的默认导出做兼容处理——也就是将原生class形式的BaseReporter包裹成一个普通可调用函数,模拟CJS模块的导出形态。
当TS输出的CJS子类(ExampleReporter)执行继承逻辑时,会通过原型链拷贝+父类构造器调用的方式实现继承,此时对被interop层包裹的“伪CJS构造函数”做无new的函数调用,就会触发原生class不允许被直接调用的语法校验,抛出对应的TypeError。
修复的核心逻辑就是调整CommonJS编译的interop规则,避免对原生ES class的默认导出做不必要的函数包裹。
TSdx构建流程适配配置
TSdx底层基于Rollup+Babel封装构建流程,无直接暴露的配置入口,但可以通过自定义Babel配置、调整TS编译参数、优化导入路径三个层面完成适配,具体步骤:
- 安装必要的Babel兼容依赖
npm i -D @babel/plugin-transform-modules-commonjs @babel/preset-env - 在项目根目录新建
babel.config.js,覆盖TSdx默认的模块编译规则,关闭对原生class的不必要包裹:module.exports = (api) => { api.cache.forever() return { presets: [ [ '@babel/preset-env', { modules: 'commonjs', targets: { node: 'current' }, exclude: ['transform-classes'] } ] ], plugins: [ [ '@babel/plugin-transform-modules-commonjs', { loose: false, allowDeclareFields: true, esModules: true } ] ] } } - 调整项目根目录
tsconfig.json的编译参数,避免TS层将ES class降级为普通构造函数:{ "compilerOptions": { "target": "ES2018", "module": "ESNext", "moduleResolution": "Node", "downlevelIteration": true, "isolatedModules": true }, "include": ["src", "test"] } - 修正Jest BaseReporter的导入路径,减少内部路径带来的兼容问题:
将原本直接引用内部构建产物的导入,替换为Jest官方对外暴露的导出入口,避免内部产物的模块格式带来额外兼容成本:// 替换原内部路径导入 // import BaseReporter from '@jest/reporters/build/base_reporter' import { BaseReporter } from '@jest/reporters' export class ExampleReporter extends BaseReporter { // 自定义Reporter逻辑实现 }
验证方式
重新执行TSdx watch构建流程,在Node REPL中重新执行Reporter类的实例化操作,不会再抛出构造器调用的相关报错,即可完成适配。
内容的提问来源于stack exchange,提问作者sschmeck
相关产品推荐
相关产品推荐

