【问题标题】:Class constructor cannot be invoked without 'new' for TSdx package对于 TSdx 包,如果没有“new”,则无法调用类构造函数
【发布时间】:2021-01-13 20:48:55
【问题描述】:

我使用TSdx 为小型Jest 记者创建了一个npm 包。如果我在另一个项目中使用该包,我会收到以下错误。

Uncaught TypeError: Class constructor BaseReporter cannot be invoked without 'new'
    at new ExampleReporter (..\dist\example-reporter.cjs.development.js:37:26)

ExampleReporter 继承自 Jest 提供的 BaseReporter 类。

import BaseReporter from '@jest/reporters/build/base_reporter';

export class ExampleReporter extends BaseReporter {
  // ...
}

Class constructor cannot be invoked without 'new'中提到的,可以通过设置Babel来修复。但我无法通过 TSdx 文档找到可行的解决方案。

如何配置 TSdx build


您可以使用手表模式重现该问题。

$ npx tsdx watch --onSuccess node .
...
  Watching for changes

Welcome to Node.js v12.18.2.
Type ".help" for more information.
> new (require('.').ExampleReporter)()
Uncaught TypeError: Class constructor BaseReporter cannot be invoked without 'new'

【问题讨论】:

  • 在没有rollout 但使用tsc 作为转译器的环境中,设置compilerOptions.target = "ES6" 可以解决此问题。但这对 TSdx 构建没有帮助。 ://

标签: typescript babeljs commonjs tsdx


【解决方案1】:

您只需设置--target node 即可解决此问题(因为默认值为browser)。

$ npx tsdx build --target node

或者,您可以将 Babel 配置文件 .babelrc 添加到您的 TDdx 项目并设置您的目标环境。

{
  "presets": [
    ["@babel/preset-env", { "targets": { "esmodules": true } }]
  ]
}

【讨论】:

    猜你喜欢
    • 2021-06-29
    • 2021-12-23
    • 2020-12-14
    • 2017-09-29
    • 2018-09-19
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    相关资源
    最近更新 更多