Skip to main content

@babel/preset-typescript

如果你使用 TypeScript,一种 JavaScript 的类型超集,推荐使用这个预设。它包含以下插件:

🌐 This preset is recommended if you use TypeScript, a typed superset of JavaScript. It includes the following plugins:

你需要为 @babel/cli 和 @babel/node 的命令行指定 --extensions ".ts" 来处理 .ts 文件。

示例​

🌐 Example

在

const x: number = 0;

出

JavaScript
const x = 0;

安装​

🌐 Installation

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

用法​

🌐 Usage

🌐 With a configuration file (Recommended)

babel.config.json
{
"presets": ["@babel/preset-typescript"]
}

通过 CLI​

🌐 Via CLI

Shell
babel --presets @babel/preset-typescript script.ts

通过 Node API​

🌐 Via Node API

JavaScript
require("@babel/core").transformSync("code", {
presets: ["@babel/preset-typescript"],
filename: 'script.ts',
});

选项​

🌐 Options

jsxPragma​

string,默认值为 React

替换在编译 JSX 表达式时使用的函数。这样我们就能知道这个导入不是类型导入,不应该被移除。

🌐 Replace the function used when compiling JSX expressions. This is so that we know that the import is not a type import, and should not be removed.

jsxPragmaFrag​

string,默认值为 React.Fragment

替换在编译 JSX 片段表达式时使用的函数。这样我们就知道这个导入不是类型导入,也不应该被移除。

🌐 Replace the function used when compiling JSX fragment expressions. This is so that we know that the import is not a type import, and should not be removed.

allowNamespaces​

boolean 使用 @babel/plugin-transform-typescript 设置的默认值。

已添加于:v7.6.0

🌐 Added in: v7.6.0

启用 TypeScript 命名空间的编译。

🌐 Enables compilation of TypeScript namespaces.

allowDeclareFields​

boolean,默认值为 false

已添加于:v7.7.0

🌐 Added in: v7.7.0

注意:在 Babel 8 中,这将默认启用

启用时,只有当类型专用的类字段带有 declare 修饰符前缀时,它们才会被移除:

🌐 When enabled, type-only class fields are only removed if they are prefixed with the declare modifier:

class A {
declare foo: string; // Removed
bar: string; // Initialized to undefined
prop?: string; // Initialized to undefined
prop1!: string // Initialized to undefined
}

disallowAmbiguousJSXLike​

boolean,对 .mts 和 .cts 文件默认使用 true,其他情况默认使用 false。

已添加于:v7.16.0

🌐 Added in: v7.16.0

即使没有启用 JSX 解析,这个选项也禁止使用可能与 JSX 混淆的语法(<X> y 类型断言和 <X>() => {} 类型参数)。它在解析 .mts 和 .mjs 文件时的行为与 tsc 相同。

🌐 Even when JSX parsing is not enabled, this option disallows using syntax that would be ambiguous with JSX (<X> y type assertions and <X>() => {} type arguments). It matches the tsc behavior when parsing .mts and .mjs files.

ignoreExtensions​

boolean,默认值为 false

已添加于:v7.21.4

🌐 Added in: v7.21.4

当设置为 false 时,Babel 会自动为 *.ts、*.tsx、*.mts 和 *.cts 文件提供所需的插件。

🌐 When it is set to false, Babel will automatically provide required plugins for *.ts, *.tsx, *.mts and *.cts files.

当设置为 true 时,Babel 会提供一个通用的 TS 插件。如果你想像处理 *.tsx 一样转换源代码,可以启用 @babel/preset-react 预设,这个插件应该可以与 JSX 转换无缝配合。例如,

🌐 When it is set to true, Babel will provide a general TS plugin. If you want to transpile source as if it were *.tsx, enable the @babel/preset-react preset and this plugin should work with the JSX transform seamlessly. For example,

babel.config.json
{
"presets": ["@babel/preset-react"],
"overrides": [{
"test": "*.vue",
"presets": [
["@babel/preset-typescript"], { "ignoreExtensions": true }
]
}]
}

onlyRemoveTypeImports​

boolean,默认是 true

历史
版本变更
v7.9.0添加了 onlyRemoveTypeImports,默认值为 false
v8.0.0默认值为 true

当设置为 true 时,转换只会移除 仅类型导入(TypeScript 3.8 引入)。只有在你使用 TypeScript >= 3.8 时才应该使用这个。

🌐 When set to true, the transform will only remove type-only imports (introduced in TypeScript 3.8). This should only be used if you are using TypeScript >= 3.8.

optimizeConstEnums​

boolean,默认值为 false

已添加于:v7.15.0

🌐 Added in: v7.15.0

当设置为 true 时,Babel 会将枚举值内联,而不是使用通常的 enum 输出:

🌐 When set to true, Babel will inline enum values rather than using the usual enum output:

// Input
const enum Animals {
Fish
}
console.log(Animals.Fish);

// Default output
var Animals;

(function (Animals) {
Animals[Animals["Fish"] = 0] = "Fish";
})(Animals || (Animals = {}));

console.log(Animals.Fish);

// `optimizeConstEnums` output
console.log(0);

这个选项与 TypeScript 的 --isolatedModules 行为不同,后者会忽略 const 修饰符并将它们编译为普通枚举,并且使 Babel 的行为与 TypeScript 的默认行为保持一致。

🌐 This option differs from TypeScript's --isolatedModules behavior, which ignores the const modifier and compiles them as normal enums, and aligns Babel's behavior with TypeScript's default behavior.

不过,当 导出 一个 const enum 时,Babel 会将其编译成一个普通的对象字面量,这样在编译时就不需要依赖跨文件分析了:

🌐 However, when exporting a const enum Babel will compile it to a plain object literal so that it doesn't need to rely on cross-file analysis when compiling it:

// Input
export const enum Animals {
Fish,
}

// `optimizeConstEnums` output
export var Animals = {
Fish: 0,
};

你可以在这里阅读更多关于配置预设选项的内容。

rewriteImportExtensions​

boolean,默认值为 false

已添加于:v7.23.0

🌐 Added in: v7.23.0

当设置为 true 时,Babel 会在导入声明中将 .ts/.mts/.cts 扩展名重写为 .js/.mjs/.cjs。这个选项相当于 TypeScript 的 rewriteRelativeImportExtensions 选项。

🌐 When set to true, Babel will rewrite .ts/.mts/.cts extensions in import declarations to .js/.mjs/.cjs. This options mirrors TypeScripts's rewriteRelativeImportExtensions option.

这个选项在与 TypeScript 的 allowImportingTsExtension 选项一起使用时,可以在导入声明中写完整的相对说明符,同时使用源文件使用的相同扩展名。

🌐 This option, when used together with TypeScript's allowImportingTsExtension option, allows to write complete relative specifiers in import declarations while using the same extension used by the source files.

举个例子,假设有这样的项目结构(其中 src 包含源文件,dist 包含编译后的文件):

🌐 As an example, given this project structure (where src contains the source files, and dist the compiled files):

.
├── src
│ ├── main.ts
│ └── dep.ts
├── dist
│ ├── main.js
│ └── dep.js
├── babel.config.json
└── tsconfig.json

以及以下配置文件:

babel.config.jsontsconfig.json
{
"presets": [
["@babel/preset-typescript", {
"rewriteImportExtensions": true
}]
]
}
{
"compilerOptions": {
"lib": ["esnext"],
"noEmit": true,
"isolatedModules": true,
"moduleResolution": "nodenext",
"allowImportingTsExtensions": true
}
}

你将能够在 main.ts 中写 import x from "./dep.ts",而 Babel 在将 main.ts 编译成 main.js 时会把它转成 import x from "./dep.js"。

🌐 you will be able to write import x from "./dep.ts" in main.ts, and Babel will transform it to import x from "./dep.js" when compiling main.ts to main.js.