简体   繁体   English

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

[英]TypeScript. How prevent transpiling while using ESNext as a target in tsconfig.json?

I've already found that question and believe it should help: How to keep ES6 syntax when transpiling with Typescript , but without any luck... It's a bit different.我已经发现了这个问题并相信它应该有所帮助: How to keep ES6 syntax when transpiling with Typescript ,但没有任何运气......它有点不同。

In my case, while yarn tsc --project tsconfig.json the file with:就我而言,虽然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);

became like:变成了:

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

Eventually, how can I get the same code as I have thrown on the input?最终,我怎样才能获得与输入时相同的代码? Eg without any postprocessing.例如,没有任何后处理。

My tsconfig.json:我的 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"
  ]
}

Enabling useDefineForClassFields in tsconfig.json will generate JavaScript code that is more similar to your TypeScript source:tsconfig.json中启用useDefineForClassFields将生成与您的 TypeScript 源代码更相似的 JavaScript 代码:

{
  "compilerOptions": {
    "useDefineForClassFields": true
  }
}

Using your example:使用您的示例:

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

will be transpiled to:将被转译为:

// 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM