简体   繁体   中英

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.

In my case, while yarn tsc --project tsconfig.json the file with:

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

{
  "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:

{
  "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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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