Socket
Socket
Sign inDemoInstall

@babel/template

Package Overview
Dependencies
15
Maintainers
5
Versions
78
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @babel/template

Generate an AST from a string template.


Version published
Maintainers
5
Install size
2.52 MB
Created

Package description

What is @babel/template?

The @babel/template package is a part of the Babel toolchain that allows developers to create AST (Abstract Syntax Tree) nodes with placeholders programmatically. This is useful for code generation, transformation, and manipulation tasks where you want to produce syntactically correct code snippets based on a template with variable parts.

What are @babel/template's main functionalities?

Building AST Nodes

This feature allows you to build AST nodes using template literals with placeholders. The placeholders are then replaced with actual values to create a syntactically correct code snippet.

const template = require('@babel/template').default;
const buildRequire = template(`
  const %%importName%% = require(%%source%%);
`);
const ast = buildRequire({
  importName: template.identifier('myModule'),
  source: template.stringLiteral('my-module')
});

Using Placeholders

This feature demonstrates how to use placeholders for different parts of the code, such as function names, parameters, and bodies. The placeholders are replaced with AST nodes representing identifiers, arrays of identifiers, and block statements, respectively.

const template = require('@babel/template').default;
const buildFunction = template(`
  function %%funcName%%(%%params%%) {
    return %%body%%;
  }
`);
const ast = buildFunction({
  funcName: template.identifier('myFunction'),
  params: [template.identifier('a'), template.identifier('b')],
  body: template.blockStatement([])
});

Customizing Placeholder Patterns

This feature shows how to customize the placeholder pattern used in the template. This is useful when you want to define a specific pattern for your placeholders to avoid conflicts with other parts of the code.

const template = require('@babel/template').default;
const buildAssertion = template(`
  assert(%%test%%, '%%errorMessage%%');
`, {
  placeholderPattern: /^%%[a-zA-Z0-9_]+%%$/
});
const ast = buildAssertion({
  test: template.binaryExpression('===', template.identifier('a'), template.numericLiteral(3)),
  errorMessage: template.stringLiteral('a is not 3')
});

Other packages similar to @babel/template

Readme

Source

@babel/template

Generate an AST from a string template or template literal.

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

Install

npm install --save-dev @babel/template

String Usage

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

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

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

console.log(generate(ast).code);
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");
`);

which will parse and return the AST directly.

Template Literal Usage

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

const fn = template`
  var IMPORT_NAME = require('${"my-module"}');
`);

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

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

@babel/template accepts all of the options from babylon, 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.
placeholderWhitelist

Type: Set<string> Default: undefined

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]+$/

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 @babel/template 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.

FAQs

Last updated on 23 Apr 2018

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc