Search code examples
javascripttypescriptecmascript-6tsconfigcreate-react-app

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.


Solution

  • Unfortunately, there isn't a way to do convert dependencies from ES6 to ES5. That option in tsconfig.json only affects how TypeScript code is transpiled. What you should do is use an ES5 version of your helper-from-node-modules. For example, Angular is distributed with several packages, for ES5 (umd), ES5, ES6 ... Then, in the package.json of the library there are options to tell the packager (usually webpack) what version to use, depending on the target use for TypeScript.

    If the library you're using does not support that, the only option you have is to transpile it to ES5 yourself, maybe using babel, or use an alternative. Is is strange, however, for a library to be only distributed as ES6.