Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best solution for transpiling Typescript into ES6 without transpiling of Async?

sorry the title perhaps makes you confused, let me explain of it:

our JS environment is a little bit special, fully ES6 support without native generator function* and yield, so the Typescript code:

async test(): Promise {
    return await Promise.resolve();
}

will be Transpiled into ES6:

function test() {
    return __awaiter(this, void 0, void 0, function* () { return yield Promise.resolve(); });
}

but, wryly... our env does not support native generator.. and, also we can't transpile TS into ES5, because there a few of libs referenced by the proj are ES6 modules, so if you transpile TS into ES5, the class can't be inherited (ES5 uses __extends to do this)

so I'm finding a solution to transpile our TS codes into ES6 but with all async in it transpiled into ES5 like style (tslib.js)

I can accept whatever solutions, npm / node / post scripts / TS features whatever, what I need is clues! thanks guys.

like image 814
SexyBoooom Avatar asked Dec 11 '25 02:12

SexyBoooom


1 Answers

Thanks to @ecraig12345 for the tips.

Actually to achieve this, you have to use Babel plugin to transpile the JS generated from TS source again.

The steps:

1, normally compile and output JS files from your TS project.

2, use npm to install Babel and related plugins:

@babel/cli

@babel/core

@babel/runtime

@babel/plugin-transform-for-of

@babel/plugin-transform-regenerator

@babel/plugin-transform-runtime

3, edit your .babelrc file and use this content: { "plugins": [ "@babel/plugin-transform-for-of", "@babel/plugin-transform-regenerator", "@babel/plugin-transform-runtime" ] }

4, edit your tasks.json of your TS project: { .... "tasks": [ { "label": "deployTs", "group": "build", "type": "shell", "command": "tsc TS_OUTPUT_JS_FOLDER/ --module commonjs --target es6" }, { "label": "deployFinal", "group": "build", "type": "shell", "command": "npx babel TS_OUTPUT_JS_FOLDER/ -d RE_TRANSPILE_OUTPUT_FOLDER/", "dependsOn": ["depolyTs"], "dependsOrder": "sequence" }, .... ] .... }

5, and then just execute deployFinal task by menu Terminal > Run Tasks, and the task will first compile TS and then run Babel to transpile async syntax in the output folder step by step.

Have fun.

like image 192
SexyBoooom Avatar answered Dec 14 '25 03:12

SexyBoooom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!