是否有可能在compilerOptions中有多个目标?

Rok*_*545 6 javascript typescript angular

很抱歉,如果这是一个nobb问题,但我正在构建一个Angular应用程序,而我当前的tsconfig.json文件在'compilerOptions'中将'es6'作为'target':

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "types" : []
  },
  "exclude": [
    "node_modules"
  ]
}
Run Code Online (Sandbox Code Playgroud)

是否有可能有多个目标?例如,我可以添加es5吗?我只是因为我正在阅读为es5编写的教程,但是由于我的项目的当前状态,我需要使用es6 - 即,我无法降级.我的所有代码都必须符合es6 - 如果两者都包括在内,我会想象我的代码可以符合es5和es6.

小智 9

请记住,您还可以创建多个tsconfig文件,并使用extends功能创建一个覆盖大多数元素的基本tsconfig,然后创建两个覆盖目标的目标tsconfig.

基本tsconfig:

{
    "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "types" : []
   },
   "exclude": [
     "node_modules"
   ]
}
Run Code Online (Sandbox Code Playgroud)

ES5 tsconfig:

{
    "extends": "./base.json"
    "compilerOptions": {
        "target": "es5"
    }
}
Run Code Online (Sandbox Code Playgroud)

ES6 tsconfig:

{
    "extends": "./base.json"
    "compilerOptions": {
        "target": "es6"
    }
}
Run Code Online (Sandbox Code Playgroud)

那么你只需要运行你需要的任何目标: tsc -p ./es6.json

这并不意味着您的代码将同时符合两者; 但是,您可以选择outDir为每个扩展基础的tsconfig 添加一个属性,并将输出编译为单独的目录.


Ale*_*sky 5

您只能为配置指定一个 目标。target的属性接受compilerOptions单个字符串值。

指定ES5为目标不会限制您使用 ES6 或更高版本编写源代码,它只是确保编译后的代码与仅理解 ES5 或更低版本的客户端兼容。诸如 lambda 表达式之类的功能将被编译为函数表达式。

诸如之类的表达式const foo = (bar) => bar.replace('\t', '');将被编译为var foo = function (bar) { return bar.replace('\t', ''); };目标设置为ES5.

如果您需要将目标编译为 ES5 或 ES6,实际上取决于使用您的应用程序的设备/浏览器,就兼容性而言,ES5 此时肯定是一个更“安全”的选择。这是一个很好的资源,用于确定ES6 浏览器的可比性

希望这有助于澄清事情!