Thursday 28 February 2019

Typescript transpile es6 .js dependency to es5

I have a hypothetical Typescript file in my project (simplified example).

Utils.ts:

import * as HelperFromNodeModules from 'helper-from-node-modules';

class Utils {
  static foo() {
    return HelperFromNodeModules.parse(...);
  }
}

Importing helper-from-node-modules consists of a Javascript file.

helper-from-node-modules.js:

const dep = require('foo');
function parse(...) {
   return bar.map((e) => {...});
}

And from @types/helper-from-node-modules index.d.ts:

export function parse(...);

The tsconfig.json among other things contains the following:

{
  ...
  "target": "es5",
  "lib": ["es2015.collection","es6", "dom"],
  "sourceMap": true,
  "allowJs": true,
  ...
}

So my problem is the Typescript compiler's output file is a giant concatenation of my compiled source code plus all of the decencies. Since helper-from-node-modules was always a .js file, the compiler seems to just append its contents to the output file. So, despite "target": "es5" the output file still contains es6 artifacts like const and (e) => {...}, resulting in errors with things later that expect strictly es5 javascript.

Is there is a way to tell the Typescript compiler/transpiler to output es5 on the javascript dependencies as well?

Context if you care:

I made the horrible mistake of using react-create-app-typescript and react-scripts-ts as the boilerplate for my React app. The webpack stack built in is very opinionated on where source code should come from and that the compiled source must be es5. The minifier/uglifier packaged will crash if attempting to minify any es6 artifacts. I know I can run npm run-script eject and modify the various config scripts but I am trying to avoid that mess. I would love to just get the source to compile to es6 and not mess with their webpack stack.



from Typescript transpile es6 .js dependency to es5

No comments:

Post a Comment