@babel/core
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, 选项?: Object, callback: Function)
¥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.
babel.transform(code, options, function(err, result) {
result; // => { code, map, ast }
});
示例
¥Example
babel.transform("code();", options, function(err, result) {
result.code;
result.map;
result.ast;
});
在 Babel 6 中,这个方法是同步的,不存在 transformSync
。为了向后兼容,如果没有给出回调,此函数将同步运行。如果你从 Babel 7 开始并且需要同步行为,请使用 transformSync
,因为这种向后兼容性将在 Babel 8 中被删除。
¥In Babel 6, this method was synchronous and transformSync
did not exist. For backward-compatibility, this function will behave synchronously if no callback is given. If you're starting with Babel 7 and need synchronous behavior, please use transformSync
since this backward-compatibility will be dropped in Babel 8.
transformSync
babel.transformSync(code: string, 选项?: Object)
¥babel.transformSync(code: string, options?: Object)
转换传入的 code
。返回带有生成的代码、源映射和 AST 的对象。
¥Transforms the passed in code
. Returning an object with the generated code,
source map, and AST.
babel.transformSync(code, options); // => { code, map, ast }
示例
¥Example
var result = babel.transformSync("code();", options);
result.code;
result.map;
result.ast;
transformAsync
babel.transformAsync(code: string, 选项?: Object)
¥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.
babel.transformAsync(code, options); // => Promise<{ code, map, ast }>
示例
¥Example
babel.transformAsync("code();", options).then(result => {
result.code;
result.map;
result.ast;
});
transformFile
babel.transformFile(filename: string, 选项?: Object, callback: Function)
¥babel.transformFile(filename: string, options?: Object, callback: Function)
异步转换文件的全部内容。
¥Asynchronously transforms the entire contents of a file.
babel.transformFile(filename, options, callback);
示例
¥Example
babel.transformFile("filename.js", options, function(err, result) {
result; // => { code, map, ast }
});
transformFileSync
babel.transformFileSync(filename: string, 选项?: Object)
¥babel.transformFileSync(filename: string, options?: Object)
babel.transformFile
的同步版本。返回 filename
的转换内容。
¥Synchronous version of babel.transformFile
. Returns the transformed contents of
the filename
.
babel.transformFileSync(filename, options); // => { code, map, ast }
示例
¥Example
babel.transformFileSync("filename.js", options).code;
transformFileAsync
babel.transformFileAsync(filename: string, 选项?: Object)
¥babel.transformFileAsync(filename: string, options?: Object)
Promise 版本 babel.transformFile
。返回 filename
转换后的内容的 promise。
¥Promise version of babel.transformFile
. Returns a promise for the transformed
contents of the filename
.
babel.transformFileAsync(filename, options); // => Promise<{ code, map, ast }>
示例
¥Example
babel.transformFileAsync("filename.js", options).then(result => {
result.code;
});
transformFromAst
babel.transformFromAst(ast:对象,代码?:字符串,选项?:对象,回调:函数):文件节点 | 无效的
¥babel.transformFromAst(ast: Object, code?: string, options?: Object, callback: Function): FileNode | null
给定一个 AST,转换它。
¥Given an AST, transform it.
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;
});
在 Babel 6 中,这个方法是同步的,不存在 transformFromAstSync
。为了向后兼容,如果没有给出回调,此函数将同步运行。如果你从 Babel 7 开始并且需要同步行为,请使用 transformFromAstSync
,因为这种向后兼容性将在 Babel 8 中被删除。
¥In Babel 6, this method was synchronous and transformFromAstSync
did not exist. For backward-compatibility, this function will behave synchronously if no callback is given. If you're starting with Babel 7 and need synchronous behavior, please use transformFromAstSync
since this backward-compatibility will be dropped in Babel 8.
transformFromAstSync
babel.transformFromAstSync(ast: Object, code?: string, 选项?: Object)
¥babel.transformFromAstSync(ast: Object, code?: string, options?: Object)
给定一个 AST,转换它。
¥Given an AST, transform it.
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, 选项?: Object)
¥babel.transformFromAstAsync(ast: Object, code?: string, options?: Object)
给定一个 AST,转换它。
¥Given an AST, transform it.
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, 选项?: Object, callback: Function)
¥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.
在 Babel 7 的早期 beta 中,这种方法是同步的,parseSync
是不存在的。为了向后兼容,如果没有给出回调,此函数将同步运行。如果你从 Babel 7 稳定版开始并且需要同步行为,请使用 parseSync
,因为这种向后兼容性将在 Babel 8 中被删除。
¥In Babel 7's early betas, this method was synchronous and parseSync
did not
exist. For backward-compatibility, this function will behave synchronously if
no callback is given. If you're starting with Babel 7 stable and need
synchronous behavior, please use parseSync
since this backward-compatibility
will be dropped in Babel 8.
parseSync
babel.parseSync(code: string, 选项?: Object)
¥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, 选项?: Object)
¥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(选项?: Object)
¥babel.loadOptions(options?: Object)
完全解析 Babel 的选项,产生一个选项对象,其中:
¥Resolve Babel's options fully, resulting in an options object where:
-
opts.plugins
是Plugin
实例的完整列表。¥
opts.plugins
is a full list ofPlugin
instances. -
opts.presets
为空,所有预设都被展平为opts
。¥
opts.presets
is empty and all presets are flattened intoopts
. -
它可以安全地传递回 Babel。像
"babelrc"
这样的字段被设置为false
,这样以后对 Babel 的调用就不会再次尝试加载配置文件。¥It can be safely passed back to Babel. Fields like
"babelrc"
have been set tofalse
so that later calls to Babel will not make a second attempt to load config files.
Plugin
实例并不意味着直接操作,但调用者通常会将这个 opts
序列化为 JSON,以将其用作表示 Babel 已接收选项的缓存键。对此进行缓存并不能 100% 保证正确失效,但它是我们目前拥有的最好的。
¥Plugin
instances aren't meant to be manipulated directly, but often
callers will serialize this opts
to JSON to use it as a cache key representing
the options Babel has received. Caching on this isn't 100% guaranteed to
invalidate properly, but it is the best we have at the moment.
loadPartialConfig
babel.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.
除了标准 选项 之外,此函数还接受一个附加选项作为选项对象的一部分: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
- 文件相关配置 文件的路径(如果有的话)。¥
babelrc: string | void
- The path of the file-relative configuration file, if there was one. -
babelignore: string | void
-.babelignore
文件的路径(如果有的话)。¥
babelignore: string | void
- The path of the.babelignore
file, if there was one. -
config: string | void
- 项目范围的配置文件 文件的路径(如果有的话)。¥
config: string | void
- The path of the project-wide config file file, if there was one. -
options: ValidatedOptions
- 部分解决的选项,可以被操纵并再次传回 Babel。¥
options: ValidatedOptions
- The partially resolved options, which can be manipulated and passed back to Babel again.-
plugins: Array<ConfigItem>
- 见下文。¥
plugins: Array<ConfigItem>
- See below. -
presets: Array<ConfigItem>
- 见下文。¥
presets: Array<ConfigItem>
- See below. -
它可以安全地传递回 Babel。像
"babelrc"
这样的选项已设置为 false,以便以后对 Babel 的调用不会再次尝试加载配置文件。¥It can be safely passed back to Babel. Options like
"babelrc"
have been set to false so that later calls to Babel will not make a second attempt to load config files.
-
-
hasFilesystemConfig(): boolean
- 检查解析的配置是否从文件系统加载了任何设置。¥
hasFilesystemConfig(): boolean
- Check if the resolved config loaded any settings from the filesystem. -
fileHandling
- 这设置为"transpile"
、"ignored"
或"unsupported"
,以指示调用者如何处理此文件。¥
fileHandling
- This is set to"transpile"
,"ignored"
, or"unsupported"
to indicate to the caller what to do with this file. -
files
- 为构建结果配置而读取的Set
文件路径,包括项目范围的配置文件、本地配置文件、扩展配置文件、忽略文件等。对于实现监视模式或缓存失效很有用。¥
files
- ASet
of file paths that were read to build the resulting config, including project wide config files, local config files, extended config files, ignore files, etc. Useful for implementing watch mode or cache invalidation.
ConfigItem
实例公开属性以自省值,但每个项目都应被视为不可变的。如果需要更改,则应从列表中删除该项目并替换为正常的 Babel 配置值,或替换为 babel.createConfigItem
创建的替换项目。有关 ConfigItem
字段的信息,请参阅该函数。
¥ConfigItem
instances expose properties to introspect the values, but each
item should be treated as immutable. If changes are desired, the item should be
removed from the list and replaced with either a normal Babel config value, or
with a replacement item created by babel.createConfigItem
. See that
function for information about ConfigItem
fields.
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
- 插件的解析值。¥
value: {} | Function
- The resolved value of the plugin. -
options: {} | void
- 传递给插件的选项对象。¥
options: {} | void
- The options object passed to the plugin. -
dirname: string
- 选项相对于的路径。¥
dirname: string
- The path that the options are relative to. -
name: string | void
- 用户给插件实例的名称,例如plugins: [ ['env', {}, 'my-env'] ]
¥
name: string | void
- The name that the user gave the plugin instance, e.g.plugins: [ ['env', {}, 'my-env'] ]
-
file: Object | void
- 关于插件文件的信息,如果 Babel 知道的话。¥
file: Object | void
- Information about the plugin's file, if Babel knows it.-
request: string
- 用户请求的文件,例如"@babel/env"
¥
request: string
- The file that the user requested, e.g."@babel/env"
-
resolved: string
- 已解析文件的完整路径,例如"/tmp/node_modules/@babel/preset-env/lib/index.js"
¥
resolved: string
- The full path of the resolved file, e.g."/tmp/node_modules/@babel/preset-env/lib/index.js"
-
DEFAULT_EXTENSIONS
babel.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
见 完整的选项列表在这里。