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

我已经找到了这个问题并相信它应该有所帮助:How to keep ES6 syntax when transpiling with Typescript,但没有任何运气......它有点不同。


就我而言,虽然yarn tsc --project tsconfig.json文件包含:


// ./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


class 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"

  ]

}


摇曳的蔷薇
浏览 324回答 1
1回答

皈依舞

启用useDefineForClassFieldsintsconfig.json将生成更类似于您的 TypeScript 源的 JavaScript 代码:{  "compilerOptions": {    "useDefineForClassFields": true  }}使用您的示例:// ./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.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);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript