首页 > 解决方案 > 带有修饰符的 TypeScript 构造函数参数无法使用 ts-loader 正确发出

问题描述

我开始使用使用 TypeScript/React/Storybook 构建的 Web 应用程序。我在写课程时注意到:

class MyClass {
  constructor(public a) { }
}

console.log(MyClass);

并使用 jest 运行单元测试,或使用 tsc 发出代码,它会生成预期的 JS 代码,例如:

function MyClass(a) {
  this.a = a;
}

但是当我在带有开发服务器的 Storybook 应用程序中运行它时,它会打印出如下 JS 代码:

function MyClass(a) {
  _classCallCheck(this, MyClass);
}

我在想它是否与 ts-loader 选择的 TypeScript 编译器版本有关,但无法弄清楚。我检查了安装到我的 node_modules 文件夹中的 TypeScript 版本,它是 v4.1.2,这对我来说看起来没什么问题。

我还在这里提到了剧本(并在标签中留下了“剧本”),只是因为我的应用程序与它在一起。它可能与此问题没有直接关系。

标签: reactjstypescriptstorybookts-loader

解决方案


@babel/preset-typescript如果您正在使用它,这似乎是最新版本的问题。您可以更改您的 babel 配置以使用"@babel/plugin-transform-typescript" 插件而不是@babel/preset-typescript预设。更多信息:https ://www.gitmemory.com/issue/babel/babel/8752/486541662

如果由 storybook 生成,您的 babel 配置可能如下所示:

module.exports = {
  presets: [
    ["@babel/preset-env", { targets: { node: "current" } }],
    "@babel/preset-typescript",
  ],
};

然后将其更改为:

module.exports = {
  presets: [["@babel/preset-env", { targets: { node: "current" } }]],
  plugins: ["@babel/plugin-transform-typescript"],
};


推荐阅读