Skip to main content

@babel/core

JavaScript
var babel = require("@babel/core");
import { transform } from "@babel/core";
import * as babel from "@babel/core";

所有转换都会使用你本地的配置文件。

🌐 All transformations will use your local configuration files.

transform​

babel.transform(code: string, options?: Object, callback: Function)

转换传入的 code。调用回调时会传入一个包含生成的代码、源映射和 AST 的对象。

🌐 Transforms the passed in code. Calling a callback with an object with the generated code, source map, and AST.

JavaScript
babel.transform(code, options, function(err, result) {
result; // => { code, map, ast }
});

示例

JavaScript
babel.transform("code();", options, function(err, result) {
result.code;
result.map;
result.ast;
});
info

在 Babel 6 中,这个方法是同步的,而且 transformSync 并不存在。为了向后兼容,如果没有提供回调函数,这个函数会保持同步。如果你是从 Babel 7 开始,并且需要同步行为,请使用 transformSync,因为这种向后兼容在 Babel 8 中将不再支持。

transformSync​

babel.transformSync(code: string, options?: Object)

转换传入的 code。返回一个包含生成的代码、源映射和 AST 的对象。

🌐 Transforms the passed in code. Returning an object with the generated code, source map, and AST.

JavaScript
babel.transformSync(code, options); // => { code, map, ast }

示例

JavaScript
var result = babel.transformSync("code();", options);
result.code;
result.map;
result.ast;

transformAsync​

babel.transformAsync(code: string, options?: Object)

转换传入的 code。返回一个包含生成代码、源映射和 AST 的对象的 Promise。

🌐 Transforms the passed in code. Returning an promise for an object with the generated code, source map, and AST.

JavaScript
babel.transformAsync(code, options); // => Promise<{ code, map, ast }>

示例

JavaScript
babel.transformAsync("code();", options).then(result => {
result.code;
result.map;
result.ast;
});

transformFile​

babel.transformFile(filename: string, options?: Object, callback: Function)

异步转换文件的全部内容。

🌐 Asynchronously transforms the entire contents of a file.

JavaScript
babel.transformFile(filename, options, callback);

示例

JavaScript
babel.transformFile("filename.js", options, function(err, result) {
result; // => { code, map, ast }
});

transformFileSync​

babel.transformFileSync(filename: string, options?: Object)

babel.transformFile 的同步版本。返回 filename 的转换内容。

🌐 Synchronous version of babel.transformFile. Returns the transformed contents of the filename.

JavaScript
babel.transformFileSync(filename, options); // => { code, map, ast }

示例

JavaScript
babel.transformFileSync("filename.js", options).code;

transformFileAsync​

babel.transformFileAsync(filename: string, options?: Object)

babel.transformFile 的 Promise 版本。返回一个关于 filename 转换后内容的 promise。

🌐 Promise version of babel.transformFile. Returns a promise for the transformed contents of the filename.

JavaScript
babel.transformFileAsync(filename, options); // => Promise<{ code, map, ast }>

示例

JavaScript
babel.transformFileAsync("filename.js", options).then(result => {
result.code;
});

transformFromAst​

babel.transformFromAst(ast: Object, code?: string, options?: Object, callback: Function): FileNode | null

给定一个 AST,把它转换一下。

🌐 Given an AST, transform it.

JavaScript
const sourceCode = "if (true) return;";
const parsedAst = babel.parseSync(sourceCode, {
parserOpts: { allowReturnOutsideFunction: true },
});
babel.transformFromAst(parsedAst, sourceCode, options, function(err, result) {
const { code, map, ast } = result;
});
info

在 Babel 6 中,这个方法是同步的,而且 transformFromAstSync 并不存在。为了向后兼容,如果没有提供回调函数,这个函数会以同步方式运行。如果你从 Babel 7 开始并且需要同步行为,请使用 transformFromAstSync,因为这种向后兼容将在 Babel 8 中被移除。

transformFromAstSync​

babel.transformFromAstSync(ast: Object, code?: string, options?: Object)

给定一个 AST,把它转换一下。

🌐 Given an AST, transform it.

JavaScript
const sourceCode = "if (true) return;";
const parsedAst = babel.parseSync(sourceCode, {
parserOpts: { allowReturnOutsideFunction: true },
});
const { code, map, ast } = babel.transformFromAstSync(
parsedAst,
sourceCode,
options
);

transformFromAstAsync​

babel.transformFromAstAsync(ast: Object, code?: string, options?: Object)

给定一个 AST,把它转换一下。

🌐 Given an AST, transform it.

JavaScript
const sourceCode = "if (true) return;";
babel
.parseAsync(sourceCode, { parserOpts: { allowReturnOutsideFunction: true } })
.then(parsedAst => {
return babel.transformFromAstAsync(parsedAst, sourceCode, options);
})
.then(({ code, map, ast }) => {
// ...
});

parse​

babel.parse(code: string, options?: Object, callback: Function)

给定一些代码,使用 Babel 的标准行为进行解析。引用的预设和插件会被加载,这样可选的语法插件就会自动启用。

🌐 Given some code, parse it using Babel's standard behavior. Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.

info

在 Babel 7 的早期测试版中,这个方法是同步的,而且 parseSync 并不存在。为了向后兼容,如果没有提供回调函数,这个函数会同步执行。如果你从稳定版 Babel 7 开始,并且需要同步行为,请使用 parseSync,因为这种向后兼容在 Babel 8 中会被移除。

parseSync​

babel.parseSync(code: string, options?: Object)

返回一个 AST。

🌐 Returns an AST.

给定一些代码,使用 Babel 的标准行为进行解析。引用的预设和插件会被加载,这样可选的语法插件就会自动启用。

🌐 Given some code, parse it using Babel's standard behavior. Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.

parseAsync​

babel.parseAsync(code: string, options?: Object)

返回一个 AST 的 promise。

🌐 Returns a promise for an AST.

给定一些代码,使用 Babel 的标准行为进行解析。引用的预设和插件会被加载,这样可选的语法插件就会自动启用。

🌐 Given some code, parse it using Babel's standard behavior. Referenced presets and plugins will be loaded such that optional syntax plugins are automatically enabled.

高级 API​

🌐 Advanced APIs

许多封装了 Babel 的系统喜欢自动注入插件和预设,或者覆盖选项。为了实现这个目标,Babel 提供了几个函数,可以在不进行转换的情况下部分加载配置。

🌐 Many systems that wrap Babel like to automatically inject plugins and presets, or override options. To accomplish this goal, Babel exposes several functions that aid in loading the configuration part-way without transforming.

loadOptions​

babel.loadOptions(options?: Object)

完全解析 Babel 的选项,产生一个选项对象,其中:

🌐 Resolve Babel's options fully, resulting in an options object where:

  • opts.plugins 是 Plugin 实例的完整列表。
  • opts.presets 是空的,所有预设都已合并到 opts 里。
  • 它可以安全地传回给 Babel。像 "babelrc" 这样的字段已经被设置为 false,这样以后调用 Babel 时就不会再尝试加载配置文件了。

Plugin 实例不应该被直接操作,但调用者经常会将这个 opts 序列化为 JSON,用作表示 Babel 接收到的选项的缓存键。在这个上面做缓存不能 100% 保证会正确失效,但目前这是我们能用的最好方式。

loadPartialConfig​

babel.loadPartialConfig(options?: Object): PartialConfig

为了让系统能够轻松操作和验证用户的配置,这个函数会解析插件和预设,但不会继续执行。期望调用者会获取配置的 .options,根据自己的需求进行操作,然后再传回给 Babel。

🌐 To allow systems to easily manipulate and validate a user's config, this function resolves the plugins and presets and proceeds no further. The expectation is that callers will take the config's .options, manipulate it as they see fit and pass it back to Babel again.

这个函数除了标准的 options 外,还接受 options 对象中的一个附加选项:showIgnoredFiles。
当设置为 true 时,loadPartialConfig 在文件被忽略时总是返回一个结果,而不是 null。
这很有用,因为它允许调用者访问影响此结果的文件列表,例如在监听模式下。
调用者可以根据返回的 fileHandling 属性判断文件是否被忽略。

🌐 This function accepts one additional option as part of the options object in addition to the standard options: showIgnoredFiles. When set to true, loadPartialConfig always returns a result when a file is ignored, rather than null. This is useful in order to allow the caller to access the list of files that influenced this outcome, e.g. for watch mode. The caller can determine whether a file was ignored based on the returned fileHandling property.

  • babelrc: string | void - file-relative 配置 文件的路径,如果有的话。
  • babelignore: string | void - .babelignore 文件的路径,如果有的话。
  • config: string | void - 如果有的话,项目范围配置文件 的路径。
  • options: ValidatedOptions - 部分解决的选项,可以被操纵并再次传回 Babel。
    • plugins: Array<ConfigItem> - 见下文。
    • presets: Array<ConfigItem> - 见下文。
    • 它可以安全地传回 Babel。像 "babelrc" 这样的选项已被设置为 false,这样后续对 Babel 的调用就不会再次尝试加载配置文件。
  • hasFilesystemConfig(): boolean - 检查解析的配置是否从文件系统加载了任何设置。
  • fileHandling - 这个设置为 "transpile"、"ignored" 或 "unsupported",用来告诉调用者该如何处理这个文件。
  • files - 一个包含已读取文件路径的 Set,用于生成最终配置,包括全局项目配置文件、本地配置文件、扩展配置文件、忽略文件等。对于实现监视模式或缓存失效很有用。

ConfigItem 实例可以用来查看属性的值,但每个条目都应被视为不可变的。如果需要修改,应将该条目从列表中移除,然后替换为普通的 Babel 配置值,或者使用 babel.createConfigItem 创建的替代条目。有关 ConfigItem 字段的信息,请参见该函数。

createConfigItem​

babel.createConfigItem(value: string | {} | Function | [string | {} | Function, {} | void], { dirname?: string, type?: "preset" | "plugin" }): ConfigItem

允许构建工具提前创建和缓存配置项。如果针对某个插件多次调用这个函数,Babel 会多次调用该插件的函数。如果你有一套明确的预期插件和预设要注入,建议预先构建这些配置项。

🌐 Allows build tooling to create and cache config items up front. If this function is called multiple times for a given plugin, Babel will call the plugin's function itself multiple times. If you have a clear set of expected plugins and presets to inject, pre-constructing the config items would be recommended.

ConfigItem 型​

🌐 ConfigItem type

每个 ConfigItem 都会显示 Babel 知道的所有信息。字段有:

🌐 Each ConfigItem exposes all of the information Babel knows. The fields are:

  • value: {} | Function - 插件的解析值。
  • options: {} | void - 传递给插件的选项对象。
  • dirname: string - 选项相对于的路径。
  • name: string | void - 用户给插件实例起的名字,例如 plugins: [ ['env', {}, 'my-env'] ]
  • file: Object | void - 关于插件文件的信息,如果 Babel 知道的话。
    • request: string - 用户请求的文件,例如 "@babel/env"
    • resolved: string - 已解析文件的完整路径,例如 "/tmp/node_modules/@babel/preset-env/lib/index.js"

DEFAULT_EXTENSIONS​

babel.DEFAULT_EXTENSIONS: readonly string[];

Babel 支持的默认扩展名列表(".js"、".jsx"、".es6"、".es"、".mjs"、"cjs")。 这个列表被 @babel/register 和 @babel/cli 用来确定哪些文件需要转译。 无法扩展这个列表,不过 @babel/cli 确实提供了一些方法,可以用 --extensions 支持其他扩展名。

🌐 A list of default extensions supported by babel (".js", ".jsx", ".es6", ".es", ".mjs", "cjs"). This list is used by @babel/register and @babel/cli to determine which files need transpiling. Extending this list isn't possible, however @babel/cli does provide ways to support other extensions with --extensions.

选项​

🌐 Options

在这里查看完整选项列表。

🌐 See the full option list here.