template


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

Install

 sh
npm install --save-dev @babel/template

String Usage

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

You can use two different kinds of placeholders: syntactic placeholders (e.g. %%name%%) or identifier placeholders (e.g. NAME). code>@babel/template</code 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.

Please note that syntactic placeholders were introduced in Babel 7.4.0. If you don’t control the code>@babel/template</code version (for example, when importing it from a code>@babel/core@^7.0.0</code 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):

Js中文网 – 前端进阶资源教程 www.javascriptC.com ,Babel中文文档
一个致力于帮助开发者用代码改变世界为使命的平台

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);

```javascript

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"),
});

```javascript

Output:

```javascript
const myModule = require("my-module");

.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.

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

```javascript

which will parse and return the AST directly.

### [][5]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

Js中文网 – 前端进阶资源教程 www.javascriptC.com ,Babel中文文档
一个致力于帮助开发者用代码改变世界为使命的平台

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.

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

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

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 results

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

template.smart

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

template.statements

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

template.expression

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

template.program

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

API

template(code, [opts])

code

Type: string

options

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

  • allowReturnOutsideFunction is set to true by default.
  • allowSuperOutsideMethod is set to true by default.
  • sourceType is set to module by default.
syntacticPlaceholders

Type: boolean Default: true if %%foo%%-style placeholders are used; false otherwise.

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

Type: Set<string> Default: undefined

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

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

This option is not compatible with syntacticPlaceholders: true

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

Type: boolean Default: false

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

Return value

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

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

← runtimetraverse →

来源:Js中文网 – 前端进阶资源教程
链接:https://www.javascriptc.com/docs/babel-manual/babel-template

看完两件小事

如果你觉得这篇文章对你挺有启发,我想请你帮我两个小忙:

  1. 关注我们的 画漫画的程序员 GitHub仓库,让我们成为长期关系
  2. 把这篇文章分享给你的朋友 / 交流群,让更多的人看到,一起进步,一起成长!
  3. 关注公众号 「画漫画的程序员」,公众号后台回复「资源」 免费领取我精心整理的前端进阶资源教程

JS中文网是中国领先的新一代开发者社区和专业的技术媒体,一个帮助开发者成长的社区,目前已经覆盖和服务了超过 300 万开发者,你每天都可以在这里找到技术世界的头条内容。欢迎热爱技术的你一起加入交流与学习,JS中文网的使命是帮助开发者用代码改变世界