Nahush Farkande Nahush Farkande - 28 days ago 13
TypeScript Question

Jest preprocessor for Typescript/ES6

I am trying to test A Typescript Class Using Jest. Since I need to use es6's

async/await
I need the typescript class to be compiled to es6 first and then to es5 using babel. What do I need to add to the preprocessor in order to achieve this.
My current preprocessor looks like this:

const tsc = require('typescript');

module.exports = {
process: function(src, path) {
if (path.endsWith('.ts') || path.endsWith('.tsx')) {
return tsc.transpile(
src,
{
module: tsc.ModuleKind.CommonJS,
jsx: tsc.JsxEmit.React
},
path,
[]
);
}
return src;
}
};


Do I need to add
target: tsc.ScriptTarget.ES6
?
When I do so I get an
unexpected identifier =
error in the processed code which looks like the transpiled version of my
.ts
class. What I gathered from this is that my preprocessor is compiling data to es6 but my es6 is not being transpiled to es5.
Also is there any readymade preprocessor which can do this?

Answer

The solution to this problem that I am currently using is

const tsc = require('typescript');

const babel = require('babel-core');
const jestPreset = require('babel-preset-jest');
const es2015 = require('babel-preset-es2015');
const stage3 = require('babel-preset-stage-3');

module.exports = {
    process: function (src, path) {
        if (path.endsWith('.ts') || path.endsWith('.tsx')) {
            var es6Code = tsc.transpile(
                src,
                {
                    target: tsc.ScriptTarget.ES6,
                    module: tsc.ModuleKind.CommonJS,
                    jsx: tsc.JsxEmit.React
                },
                path,
                []
            );
            return babel.transform(es6Code, {
                auxiliaryCommentBefore: ' istanbul ignore next ',
                    presets: [jestPreset, es2015, stage3],
                retainLines: true
            }).code;
        }
        return src;
    }
};

So what I am doing here is I am taking the transpiled code generated by the typescript compiler and passing it through babel, which in turn is converting my code from es6 to es5.

Comments