How to use the templateLiteral function from @babel/types

Find comprehensive JavaScript @babel/types.templateLiteral code examples handpicked from public code repositorys.

@babel/types.templateLiteral is a function that creates an AST node representing a template literal in a Babel-compatible syntax.

16
17
18
19
20
21
22
23
24
25
const toObjectExpression = obj =>
    t.objectExpression(
        Object.entries(obj).map(([key, value]) =>
            t.objectProperty(
                t.stringLiteral(key),
                t.templateLiteral(
                    [
                        t.templateElement({
                            raw: value,
                            cooked: value,
fork icon15
star icon363
watch icon0

+ 59 other calls in file

177
178
179
180
181
182
183
184
185
186
    } else if (t.isJSXExpressionContainer(node)) {
      const identifier = addMemberExpression(t, node.expression, scope);
      expressions.push(identifier);
    }
  });
  return t.templateLiteral(quasis, expressions);
}

function transformAttributes(objectExpression, element) {
  let source = 'props' in element ? element.props : element.attrs;
fork icon0
star icon9
watch icon2

+ 3 other calls in file

How does @babel/types.templateLiteral work?

@babel/types.templateLiteral is a function provided by the Babel library that generates an abstract syntax tree (AST) node representing a template literal, which is a type of string that allows for embedded expressions.

The function takes in several arguments, including an array of template element nodes and an array of expression nodes that correspond to the embedded expressions in the template literal.

The resulting AST node can then be used by Babel to perform transformations on the code.

163
164
165
166
167
168
169
170
171
    return append;
};

const prepareExpressions = (expressions, hash) => {
    if (options.stringStyle) {
        return t.templateLiteral(
            expressions
                .map((x, i) => {
                    const value = (i > 0 ? ';' : '') + `--${hash}_${i}:`;
fork icon14
star icon0
watch icon2

+ 5 other calls in file

23
24
25
26
27
28
29
30
31
32
    .program
    .body[0]
    .expression;
const objectPropertyAst = t.objectProperty(
    t.identifier('template'),
    t.templateLiteral(templateLiteralAst.quasis, templateLiteralAst.expressions)
);
traverse(sanScriptAst, {
    enter(path) {
        if (path.node.type !== 'ExportDefaultDeclaration') {
fork icon5
star icon0
watch icon2

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
const t = require("@babel/types");

// create a template literal with a placeholder
const templateLiteral = t.templateLiteral(
  [
    t.templateElement({ raw: "Hello, ", cooked: "Hello, " }),
    t.templateElement({ raw: "!", cooked: "!" }, true),
  ],
  [t.identifier("name")]
);

console.log(templateLiteral);

This will output the following AST node: css Copy code

394
395
396
397
398
399
400
401
402
403

// 3.1 single JSXTextNode => textContent = stringLiteral
if (children.length === 1 && children[0].type === 'JSXText' && children[0].value.trim()) {
    const stringLiteral = t.inherits(
        children[0].value.includes('\n') ?
            t.templateLiteral([t.templateElement({ raw: children[0].value })], []) :
            t.stringLiteral(children[0].value),
        children[0]);
    statements.push(
        t.inherits(this.builder.assignTextContentExpression(id, stringLiteral), path.node.closingElement)
fork icon1
star icon0
watch icon1

+ 6 other calls in file

180
181
182
183
184
185
186
187
188
189
  console.log('TemplateLiteralOutput', output);
  //assert(false);
}

path.replaceWith(
  BabelTypes.templateLiteral(
    quasis,
    output.expressions,
  )
  //BabelTypes.templateLiteral([], [])
fork icon1
star icon0
watch icon1

+ 3 other calls in file

321
322
323
324
325
326
327
328
329
330
    finalExpressions.push(expressions[part]);
  } else {
    quasis.push(part);
  }
});
return t.templateLiteral(quasis.map(function (quasi, index) {
  return t.templateElement({
    raw: quasi,
    cooked: quasi
  }, quasis.length === index + 1);
fork icon0
star icon1
watch icon0

31
32
33
34
35
36
37
38
39
40
) {
  path.node.elements = path.node.elements.map(({ value }) => {
    const tokens = value.split(/\%\%(\S+)\%\%/);
    const referenceIds = tokens.filter((_, i) => i % 2 === 1);

    return babelTypes.templateLiteral(
      tokens
        .filter((_, i) => i % 2 === 0)
        .map((token, i) =>
          babelTypes.templateElement({ raw: token }, i === path.node.elements.length - 1)
fork icon0
star icon0
watch icon2

+ 5 other calls in file

168
169
170
171
172
173
174
175
176
177

        // dont skip the entire node and children
        // keep children but dont re-process replaced node
        // path.skip()

        const ast = t.templateLiteral(quasis, expressions);
        ast.obfuscated = true;

        path.replaceWith(ast);
},
fork icon0
star icon0
watch icon0

+ 5 other calls in file

Other functions in @babel/types

Sorted by popularity

function icon

@babel/types.identifier is the most popular function in @babel/types (20936 examples)