简体   繁体   中英

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.

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.

The only thing that comes to my mind is hooking into the compilation process and transforming your dependencies before they get processed by TypeScript. This requires TypeScript transformers .

A transformer is a function to which the AST of your program is exposed. A basic example:

import * as ts from 'typescript';

export default (program: ts.Program) => {
    return (ctx: ts.TransformationContext) => {
        return (sourceFile: ts.SourceFile) => {
            function visitor(node: ts.Node): ts.Node {
                /**
                 * If that's the kind of node you were looking for,
                 * do something with it and return it. Otherwise:
                 */
                return ts.visitEachChild(node, visitor, ctx);
            }

            return ts.visitEachChild(sourceFile, visitor, ctx);
        };
    };
}

If you are using Webpack, you could plug it into your build pipeline in your Webpack configuration file.

webpack.config.js

const transformer = require('./your-custom-transformer');

module.exports = {
  /* ... */
  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'ts-loader', // (or 'awesome-typescript-loader')
        options: {
          getCustomTransformers: program => ({
            before: [
              transformer(program)
            ]
          })
        }
      }
    ]
  }
};

Came across this question because I needed to import some files into both Next.js and my CLI. (A common source file in two different builds.) Next.js has certain automated configuration, so I was trying to support all the things it supports so I didn't have many situations where Next.js worked and my CLI failed.

So the below solution is the Babel part. (I combined with https://github.com/vercel/next.js/tree/canary/examples/custom-server-typescript for the tsconfig part.)

Solution to transpile ES6 imports to ES5: (outside of nextjs)

from https://www.do.netcurry.com/javascript/1293/transpile-es6-modules-es5-using-babel

npm install --save-dev @babel/cli @babel/preset-env

Create .babelrc :

{
  presets: ["@babel/preset-env"]
}

add to your build script (ie you probably already have package.json script for npm run build to work)

for JSX to work (if you have any .tsx files or JSX syntax in .js files)

npm install --save-dev @babel/preset-react

and in .babelrc

{
  "presets": [
    "@babel/preset-env",
    [
      "@babel/preset-react",
      {
        "runtime": "automatic"
      }
    ]
  ]
}

for Next.js _app had to add https://github.com/uiwjs/babel-plugin-transform-remove-imports to remove CSS imports

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