为了账号安全,请及时绑定邮箱和手机立即绑定

打字稿。在 tsconfig.json 中使用 ESNext 作为目标时如何防止转译?

打字稿。在 tsconfig.json 中使用 ESNext 作为目标时如何防止转译?

摇曳的蔷薇 2022-06-16 16:40:24
我已经找到了这个问题并相信它应该有所帮助:How to keep ES6 syntax when transpiling with Typescript,但没有任何运气......它有点不同。就我而言,虽然yarn tsc --project tsconfig.json文件包含:// ./index.tsxclass Person {  public name: string;  constructor(name: string) {    this.name = name;  }  _run = () => {    console.log('I\'m running!')  }}let person = new Person('John Doe');console.log(person.name);变成了:// ./index.jsclass Person {    constructor(name) {        this._run = () => {            console.log('I\'m running!');        };        this.name = name;    }}let person = new Person('John Doe');console.log(person.name);最终,我怎样才能获得与输入时相同的代码?例如,没有任何后处理。我的 tsconfig.json:{  "compilerOptions": {    "baseUrl": ".",    "alwaysStrict": true,    "noImplicitAny": false,    "noUnusedLocals": true,    "noUnusedParameters": true,    "allowSyntheticDefaultImports": true,    "esModuleInterop": true,    "allowJs": true,    "checkJs": false,    "module": "ESNext",    "target": "ESNext",     "jsx": "react",    "moduleResolution": "node",    "types": ["node"],    "lib": ["dom", "es6", "es2017", "es2018", "es2019", "es2020","esnext"]  },  "linebreak-style": [true, "LF"],  "typeAcquisition": {    "enable": true  },  "include": [    "**/*"  ],  "exclude": [    "node_modules",    "**/*.test.ts",    "**/*.test.tsx",    "dist"  ]}
查看完整描述

1 回答

?
皈依舞

TA贡献1851条经验 获得超3个赞

启用useDefineForClassFieldsintsconfig.json将生成更类似于您的 TypeScript 源的 JavaScript 代码:


{

  "compilerOptions": {

    "useDefineForClassFields": true

  }

}

使用您的示例:


// ./index.tsx


class Person {

  public name: string;

  constructor(name: string) {

    this.name = name;

  }


  _run = () => {

    console.log('I\'m running!')

  }

}

let person = new Person('John Doe');

console.log(person.name);

将被转译为:


// index.js

"use strict";

class Person {

    name;

    constructor(name) {

        this.name = name;

    }

    _run = () => {

        console.log('I\'m running!');

    };

}

let person = new Person('John Doe');

console.log(person.name);


查看完整回答
反对 回复 2022-06-16
  • 1 回答
  • 0 关注
  • 323 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号