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 returns either a single statement, or an array of statements, depending on the parsed result.

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.statement("foo;")() returns a single statement node, and throw an exception if the result is anything but a single statement.

template.statements

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

¥template.statements("foo;foo;")() returns an array of statement nodes.

template.expression

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

¥template.expression("foo")() returns the expression node.

template.program

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

¥template.program("foo;")() returns the Program node for the template.

API

template(code, [opts])

code

类型:string

¥Type: string

选项

¥options

@babel/template 接受来自 巴贝尔解析器 的所有选项,并指定自己的一些默认值:

¥@babel/template accepts all of the options from Babel Parser, and specifies some defaults of its own:

  • allowReturnOutsideFunction 默认设置为 true

    ¥allowReturnOutsideFunction is set to true by default.

  • allowSuperOutsideMethod 默认设置为 true

    ¥allowSuperOutsideMethod is set to true by default.

  • sourceType 默认设置为 module

    ¥sourceType is set to module by default.

syntacticPlaceholders

类型:boolean 默认:true 如果使用 %%foo%% 样式的占位符;false 否则。添加于:v7.4.0

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

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

¥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 不兼容

¥This option is not compatible with 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 不兼容

¥This option is not compatible with syntacticPlaceholders: true

在查找应被视为占位符的标识符和 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.