首页 文章

打字稿转换es6 .js依赖于es5

提问于
浏览
9

我的项目中有一个假设的Typescript文件(简化示例) .

Utils.ts:

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

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

导入 helper-from-node-modules 包含一个Javascript文件 .

辅助性的节点,modules.js:

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

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

export function parse(...);

tsconfig.json 包含以下内容:

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

所以我的问题是Typescript编译器的输出文件是我编译的源代码加上所有的重要性的巨大连接 . 由于 helper-from-node-modules 始终是.js文件,因此编译器似乎只是将其内容附加到输出文件中 . 所以,尽管 "target": "es5" 输出文件仍然包含es6工件,如 const(e) => {...} ,导致以后出现严重es5 javascript的错误 .

有没有办法告诉Typescript编译器/转换器在javascript依赖项上输出es5?

Context if you care:

我犯了一个可怕的错误,使用 react-create-app-typescriptreact-scripts-ts 作为我的React应用程序的样板 . 内置的webpack堆栈非常注重源代码应该来自何处以及编译后的源 must 是es5 . 如果尝试缩小任何es6工件,则打包的minifier / uglifier将崩溃 . 我知道我可以运行 npm run-script eject 并修改各种配置脚本,但我试图避免这种混乱 . 我很想得到编译到es6的源代码,而不是弄乱他们的webpack堆栈 .

2 回答

  • 0

    不幸的是,没有办法将依赖项从ES6转换为ES5 . tsconfig.json 中的该选项仅影响TypeScript代码的转换方式 . 你应该做的是使用 helper-from-node-modules 的ES5版本 . 例如,Angular与几个软件包一起分发,用于ES5(umd),ES5,ES6 ......然后,在库的 package.json 中有一些选项可以告诉打包者(通常是webpack)使用什么版本,具体取决于目标用于TypeScript .

    如果你使用的库不支持,你唯一的选择就是自己将它转换为ES5,也许使用babel,或使用替代品 . 然而,对于仅作为ES6分发的库来说是奇怪的 .

  • 4

    我想到的唯一事情就是在编译过程中并在TypeScript处理之前转换依赖项 . 这需要TypeScript变换器 .

    变换器是程序的AST暴露的函数 . 一个基本的例子:

    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);
            };
        };
    }
    

    如果您使用的是Webpack,则可以将其插入Webpack配置文件中的构建管道中 .

    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)
                ]
              })
            }
          }
        ]
      }
    };
    

相关问题