Skip to main content

@babel/template

在计算机科学中,这被称为 quasiquotes 的实现。

🌐 In computer science, this is known as an implementation of quasiquotes.

安装​

🌐 Install

npm install --save-dev @babel/template

字符串用法​

🌐 String Usage

当把 template 当作函数并传入字符串参数时,你可以提供 占位符,这些占位符在使用模板时会被替换。

🌐 When calling template as a function with a string argument, you can provide placeholders which will get substituted when the template is used.

你可以使用两种不同的占位符:语法占位符(例如 %%name%%)或标识符占位符(例如 NAME)。@babel/template 默认支持这两种方法,但它们不能混用。如果你需要明确说明你使用的语法,可以使用 syntacticPlaceholders 选项。

🌐 You can use two different kinds of placeholders: syntactic placeholders (e.g. %%name%%) or identifier placeholders (e.g. NAME). @babel/template supports both those approaches by default, but they can't be mixed. If you need to be explicit about what syntax you are using, you can use the syntacticPlaceholders option.

请注意,语法占位符是在 Babel 7.4.0 中引入的。如果你无法控制 @babel/template 版本(例如,当它是从 @babel/core@^7.0.0 同行依赖中导入时),你必须使用标识符占位符。另一方面,语法占位符有一些优点:它们可以用在标识符会导致语法错误的地方(比如函数体的位置,或者导出声明中),并且不会与大写变量冲突(例如 new URL())。

🌐 Please note that syntactic placeholders were introduced in Babel 7.4.0. If you don't control the @babel/template version (for example, when importing it from a @babel/core@^7.0.0 peer dependency), you must use identifier placeholders. On the other hand, syntactic placeholders have some advantages: they can be used where identifiers would be a syntax error (e.g. in place of function bodies, or in export declarations), and they don't conflict with uppercase variables (e.g., new URL()).

输入(语法占位符):

🌐 Input (syntactic placeholders):

JavaScript
import template from "@babel/template";
import { generate } from "@babel/generator";
import * as t from "@babel/types";

const buildRequire = template(`
var %%importName%% = require(%%source%%);
`);

const ast = buildRequire({
importName: t.identifier("myModule"),
source: t.stringLiteral("my-module"),
});

console.log(generate(ast).code);

输入(标识符占位符):

🌐 Input (identifier placeholders):

JavaScript
const buildRequire = template(`
var IMPORT_NAME = require(SOURCE);
`);

const ast = buildRequire({
IMPORT_NAME: t.identifier("myModule"),
SOURCE: t.stringLiteral("my-module"),
});

输出:

🌐 Output:

JavaScript
const myModule = require("my-module");

.ast​

如果没有使用占位符,而且你只是想用一种简单的方式把字符串解析成 AST,你可以使用模板的 .ast 版本。

🌐 If no placeholders are in use and you just want a simple way to parse a string into an AST, you can use the .ast version of the template.

JavaScript
const ast = template.ast(`
var myModule = require("my-module");
`);

它将直接解析并返回 AST。

🌐 which will parse and return the AST directly.

模板字面量用法​

🌐 Template Literal Usage

JavaScript
import template from "@babel/template";
import { generate } from "@babel/generator";
import * as t from "@babel/types";

const source = "my-module";

const fn = template`
var IMPORT_NAME = require('${source}');
`;

const ast = fn({
IMPORT_NAME: t.identifier("myModule"),
});

console.log(generate(ast).code);

注意,占位符可以直接作为模板字面量的一部分传递,以尽可能让内容更易读,也可以传递到模板函数中。

🌐 Note that placeholders can be passed directly as part of the template literal in order to make things as readable as possible, or they can be passed into the template function.

.ast​

如果没有使用占位符,而且你只是想用一种简单的方式把字符串解析成 AST,你可以使用模板的 .ast 版本。

🌐 If no placeholders are in use and you just want a simple way to parse a string into an AST, you can use the .ast version of the template.

JavaScript
const name = "my-module";
const mod = "myModule";

const ast = template.ast`
var ${mod} = require("${name}");
`;

它将直接解析并返回 AST。注意,与前面提到的基于字符串的版本不同,由于这是一个模板字面量,使用模板字面量替换进行替换仍然是有效的。

🌐 which will parse and return the AST directly. Note that unlike the string-based version mentioned earlier, since this is a template literal, it is still valid to perform replacements using template literal replacements.

AST 结果​

🌐 AST results

@babel/template API 提供了一些灵活的 API,使创建具有预期结构的 AST 尽可能简单。每一个也都有上面提到的 .ast 属性。

🌐 The @babel/template API exposes a few flexible APIs to make it as easy as possible to create ASTs with an expected structure. Each of these also has the .ast property mentioned above.

template​

template 会根据解析结果返回一个单独的语句,或者一个语句数组。

template.smart​

这和默认的 template API 一样,根据解析结果返回单个节点或节点数组。

🌐 This is the same as the default template API, returning either a single node, or an array of nodes, depending on the parsed result.

template.statement​

template.statement("foo;")() 会返回一个单独的语句节点,如果结果不是单个语句,就会抛出异常。

template.statements​

template.statements("foo;foo;")() 返回一个语句节点数组。

template.expression​

template.expression("foo")() 返回表达式节点。

template.program​

template.program("foo;")() 返回模板的 Program 节点。

应用接口​

🌐 API

template(code, [opts])​

code​

类型:string

🌐 Type: string

options​

@babel/template 接受来自 Babel Parser 的所有选项,并指定了一些自己的默认值:

  • allowReturnOutsideFunction 默认设置为 true。
  • allowSuperOutsideMethod 默认设置为 true。
  • sourceType 默认设置为 module。

syntacticPlaceholders​

类型:boolean 默认:如果使用 %%foo%% 风格的占位符,则为 true;否则为 false。 新增于:v7.4.0

🌐 Type: boolean Default: true if %%foo%%-style placeholders are used; false otherwise. Added in: v7.4.0

当此选项为 true 时,你可以使用 %%foo%% 在模板中标记占位符。当它为 false 时,占位符由 placeholderWhitelist 和 placeholderPattern 选项确定。

🌐 When this option is true, you can use %%foo%% to mark placeholders in your templates. When it is false, placeholders are identifiers determined by the placeholderWhitelist and placeholderPattern options.

placeholderWhitelist​

类型:Set<string> 默认:undefined

🌐 Type: Set<string> Default: undefined

这个选项与 syntacticPlaceholders: true 不兼容

一组用于自动接受的占位名称。列表中的项目不需要与给定的占位符模式匹配。

🌐 A set of placeholder names to automatically accept. Items in this list do not need to match the given placeholder pattern.

placeholderPattern​

类型:RegExp | false 默认:/^[_$A-Z0-9]+$/

🌐 Type: RegExp | false Default: /^[_$A-Z0-9]+$/

这个选项与 syntacticPlaceholders: true 不兼容

在搜索应被视为占位符的 Identifier 和 StringLiteral 节点时要寻找的模式。'false' 将完全禁用占位符搜索,只保留 'placeholderWhitelist' 的值来查找占位符。

🌐 A pattern to search for when looking for Identifier and StringLiteral nodes that should be considered placeholders. 'false' will disable placeholder searching entirely, leaving only the 'placeholderWhitelist' value to find placeholders.

preserveComments​

类型:boolean 默认:false

🌐 Type: boolean Default: false

将此设置为 true 以保留 code 参数中的任何评论。

🌐 Set this to true to preserve any comments from the code parameter.

返回值​

🌐 Return value

默认情况下,@babel/template 会返回一个 function,可以用一个可选的替换对象来调用它。使用示例请参见使用部分。

🌐 By default @babel/template returns a function which is invoked with an optional object of replacements. See the usage section for an example.

使用 .ast 时,AST 会直接返回。

🌐 When using .ast, the AST will be returned directly.