Skip to main content

@babel/preset-typescript

如果你使用 JavaScript 的类型化超集 TypeScript,建议使用此预设。它包括以下插件:

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

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

¥You will need to specify --extensions ".ts" for @babel/cli & @babel/node cli's to handle .ts files.

示例

¥Example

输入

¥In

const x: number = 0;

输出

¥Out

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

isTSX

boolean,默认为 false

¥boolean, defaults to false

强制启用 jsx 解析。否则尖括号将被视为 typescript 的旧版类型断言 var foo = <string>bar;。此外,isTSX: true 需要 allExtensions: true

¥Forcibly enables jsx parsing. Otherwise angle brackets will be treated as typescript's legacy type assertion var foo = <string>bar;. Also, isTSX: true requires allExtensions: true.

jsxPragma

string,默认为 React

¥string, defaults to 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

¥string, defaults to 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.

allExtensions

boolean,默认为 false

¥boolean, defaults to false

表示每个文件都应该被解析为 TS、TSX 或没有 JSX 歧义的 TS(取决于 isTSXdisallowAmbiguousJSXLike 选项)。

¥Indicates that every file should be parsed as TS, TSX, or as TS without JSX ambiguities (depending on the isTSX and disallowAmbiguousJSXLike options).

allowNamespaces

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

¥boolean, uses the default set by @babel/plugin-transform-typescript.

添加于:v7.6.0

¥Added in: v7.6.0

启用 TypeScript 命名空间的编译。

¥Enables compilation of TypeScript namespaces.

allowDeclareFields

boolean,默认为 false

¥boolean, defaults to false

添加于:v7.7.0

¥Added in: v7.7.0

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

¥NOTE: This will be enabled by default in 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

¥boolean, defaults to true for .mts and .cts files and to false otherwise.

添加于: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

¥boolean, defaults to 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,默认为 false

¥boolean, defaults to false

添加于:v7.9.0

¥Added in: v7.9.0

当设置为 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

¥boolean, defaults to 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,
};

你可以阅读有关配置预设选项 此处 的更多信息。

¥You can read more about configuring preset options here.

rewriteImportExtensions

boolean,默认为 false

¥boolean, defaults to false

添加于:v7.23.0

¥Added in: v7.23.0

当设置为 true 时,Babel 会将导入声明中的 .ts/.mts/.cts 扩展重写为 .js/.mjs/.cjs

¥When set to true, Babel will rewrite .ts/.mts/.cts extensions in import declarations to .js/.mjs/.cjs.

当与 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

并使用以下配置文件:

¥and with the following configuration files:

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.