@babel/generator
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
将 Babel AST 转换为代码。
安装
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/generator
yarn add --dev @babel/generator
pnpm add --save-dev @babel/generator
bun add --dev @babel/generator
用法
JavaScript
import { parse } from "@babel/parser";
import { generate } from "@babel/generator";
const code = "class Example {}";
const ast = parse(code);
const output = generate(
ast,
{
/* options */
},
code
);
信息
AST 中不会保留空格或换行符等符号。当 Babel 生成器从 AST 生成代码时,输出格式无法保证。
解析器插件支持
Babel 生成器支持除 estree 外所有列出的 Babel 解析器插件。请注意解析器插件不会转换代码。例如,如果将 JSX <div></div> 传递给 Babel 生成器,结果中仍会包含 div JSX 元素。
JavaScript
import { parse } from "@babel/parser";
import { generate } from "@babel/generator";
const code = "const Example = () => <div>example</div>";
const ast = parse(code, { plugins: ["jsx" ] });
const output = generate(
ast,
).code;
// true
output.includes("<div>");
API
Babel 生成器仅包含一个 generate 函数,可通过多种方式导入。
JavaScript
const generate = require("@babel/generator");
const { generate } = require("@babel/generator");
import { generate } from "@babel/generator";
选项
History
| Version | Changes |
|---|---|
| v8.0.0 | Removed importAttributesKeyword |
| v7.26.0 | Added experimental_preserveFormat |
| v7.22.0 | Added importAttributesKeyword |
| v7.21.0 | Added inputSourceMap |
格式化输出选项:
| name | type | default | description |
|---|---|---|---|
| auxiliaryCommentAfter | string | Optional string to add as a block comment at the end of the output file | |
| auxiliaryCommentBefore | string | Optional string to add as a block comment at the start of the output file | |
| comments | boolean | true | Should comments be included in output |
| compact | boolean or 'auto' | opts.minified | Set to true to avoid adding whitespace for formatting |
| concise | boolean | false | Set to true to reduce whitespace (but not as much as opts.compact) |
| decoratorsBeforeExport | boolean | Set to true to print decorators before export in output. | |
| filename | string | Used in warning messages | |
| importAttributesKeyword (⚠️ removed in Babel 8) | "with", "assert", or "with-legacy" | The import attributes/assertions syntax to use. "with" for import "..." with { type: "json" }, "assert" for import "..." assert { type: "json" }, and "with-legacy" for import "..." with type: "json". When not specified, @babel/generator will try to match the style in the input code based on the AST shape. | |
| jsescOption | object | Use jsesc to process literals. jsesc is applied to numbers only if jsescOption.numbers (added in v7.9.0) is present. You can customize jsesc by passing options to it. | |
| jsonCompatibleStrings | boolean | false | Set to true to run jsesc with "json": true to print "\u00A9" vs. "©"; |
| minified | boolean | false | Should the output be minified |
| retainFunctionParens | boolean | false | Retain parens around function expressions (could be used to change engine parsing behavior) |
| retainLines | boolean | false | Attempt to use the same line numbers in the output code as in the source code (helps preserve stack traces) |
| shouldPrintComment | function | opts.comments | Function that takes a comment (as a string) and returns true if the comment should be included in the output. By default, comments are included if opts.comments is true or if opts.minified is false and the comment contains @preserve or @license |
| recordAndTupleSyntaxType | 'hash' or 'bar' | 'hash' | For use with the recordAndTuple token. |
| topicToken | '%' or '#' | The token to use with Hack-pipe topic references. This is required when there are any TopicReference nodes. |
Source map 选项:
| name | type | default | description |
|---|---|---|---|
| sourceMaps | boolean | false | Enable generating source maps |
| inputSourceMap | string or object | The input source map | |
| sourceRoot | string | A root for all relative URLs in the source map | |
| sourceFileName | string | The filename for the source code (i.e. the code in the code argument). This will only be used if code is a string. |
实验性选项:
警告
实验性选项的行为可能在_次要_版本中出现破坏性变更。
| name | type | default | description | experimental reason |
|---|---|---|---|---|
| experimental_preserveFormat | boolean | false | When set to true, the generator will try to preserve location of all the nodes and tokens that are present both in the input and output code. To use this option, you currently need to enable the retainLines: true generator option, and the tokens: true and createParenthesizedExpressions: true parser options. | This option will graduate to stable once it supports a mode that does not require preserving line numbers, but just relative positions of tokens. |
返回结果
当启用 sourceMaps 选项时,generate API 会返回包含源代码和 source map 信息的对象,其字段包括:
-
code: string- 根据 AST 生成的输出源代码 -
map: EncodedSourceMap | null- 以编码形式输出的 source map(惰性求值) -
decodedMap: DecodedSourceMap | undefined- 以解码形式输出的 source map(惰性求值) -
rawMappings: Mapping[]- 用于生成 source map 的高级映射对象,包含所有记录的分段(惰性求值)
多源 AST 处理
大多数情况下,Babel 会进行输入文件到输出文件的 1:1 转换。但当处理由多个源(如 JS 文件、模板等)构建的 AST 时,若需 source map 正确反映原始来源,需向 generate 的 code 参数传递对象:键为源文件名,值为源文件内容。
以下是一个示例:
JavaScript
import { parse } from "@babel/parser";
import { generate } from "@babel/generator";
const a = "var a = 1;";
const b = "var b = 2;";
const astA = parse(a, { sourceFilename: "a.js" });
const astB = parse(b, { sourceFilename: "b.js" });
const ast = {
type: "Program",
body: [].concat(astA.program.body, astB.program.body),
};
const { code, map } = generate(
ast,
{ sourceMaps: true },
{
"a.js": a,
"b.js": b,
}
);
// Sourcemap will point to both a.js and b.js where appropriate.