【问题标题】:How to prevent TypeScript from transpiling classes to ES5?如何防止 TypeScript 将类转换为 ES5?
【发布时间】:2023-02-02 16:49:41
【问题描述】:

我有这样的代码:

import { SuperClass } from 'some-library';

export class MyClass extends SuperClass {
  constructor() {
    super();
  }
}

该程序失败并出现如下错误:

        var _this = _super.call(this)) || this;
                           ^

TypeError: Class constructor SuperClass cannot be invoked without 'new'

正如here 所回答的,这个问题是由于 TypeScript 将类转换为 ES5,而 SuperClass 是一个 ES6 类。

引用的答案说将 TypeScript 的“目标”选项设置为 es6 应该可以修复它。但是,如果我这样做,TypeScript 仍会输出 ES5 类。将“目标”设置为“es2018”或“2020”也无济于事。无论我做什么,输出都是这样的:

var MyClass = /** @class */ (function (_super) {
    __extends(MyClass, _super);
    function MyClass() {

这是我的 tsconfig.json:

{
    "compilerOptions": {
        "target": "ES2018",
        "module": "commonjs",
        "lib": ["es2018"],
        "composite": true
    },
    "include": ["*.ts"]
}

如何使 TypeScript 输出 ES6 类?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    将此 --target es6 添加到您的命令行参数或

        "compilerOptions": {
            "target": "ES2016", \ you can also try using "esnext"
             ...
        }
       ...
    }```
    
    

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 2016-04-21
      • 2018-10-09
      • 2017-11-08
      • 1970-01-01
      • 1970-01-01
      • 2016-10-20
      • 2016-09-02
      • 2023-02-09
      相关资源
      最近更新 更多