Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
How to convert a TemplateLiteral AST node back into template string source code?

So I am working through "normalizing" a JS AST in certain ways to make transpilation easier into a particular target language. So I am having to learn the inner details of the AST. Then for testing, I am converting it back into JS source code, using print functions. I have handled pretty much every case so far, but the TemplateLiteral seems like it's a strange structure.

For example, you have this template string:

const str = 'const b83 = `foo${a100} bar ${b82}`'

Parse that str into an AST and you get this structure:

{
  "type": "TemplateLiteral",
  "start": 2692,
  "end": 2715,
  "expressions": [
    {
      "type": "Identifier",
      "start": 2698,
      "end": 2702,
      "name": "a100"
    },
    {
      "type": "Identifier",
      "start": 2710,
      "end": 2713,
      "name": "b82"
    }
  ],
  "quasis": [
    {
      "type": "TemplateElement",
      "start": 2693,
      "end": 2696,
      "value": {
        "raw": "foo",
        "cooked": "foo"
      },
      "tail": false
    },
    {
      "type": "TemplateElement",
      "start": 2703,
      "end": 2708,
      "value": {
        "raw": " bar ",
        "cooked": " bar "
      },
      "tail": false
    },
    {
      "type": "TemplateElement",
      "start": 2714,
      "end": 2714,
      "value": {
        "raw": "",
        "cooked": ""
      },
      "tail": true
    }
  ]
}

Notice, the "expressions" and "quasis" are not interlaced, they are made into separate arrays. How am I to go back and properly put them in the right order to regenerate the template string source code? Assume this AST node might be part of a larger AST, and the tree might be rewritten, so any information you use regarding the start and end text positions will only be useful from a relative, not absolute, perspective. I am just not quite sure the best way to read the start and end to re-interlace the expressions and quasis.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You're always going to have quasis.length == expressions.length+1. You just take the first quasi, then the first expression, then the next quasi, then the next expression, etc., until the last quasi.

about 4 years ago · Juan Pablo Isaza Denunciar

0

function getResultFromTemplateLiteral(ret, path) {


    const { expressions, quasis } = ret

    // 拼接模板
    let str = ''
    for (let i = 0; i < quasis.length; i++) {
        if (i) {
            str += '__' + expressions[i - 1].name + '__'
        }
        str += quasis[i].value.cooked
    }

    // 收集变量引用
    const expMap = new Map()

    for (let i = 0; i < expressions.length; i++) {
        const { name } = expressions[i]

        if (!expMap.has(name)) {
            const ref = path.scope.getBinding(name)
            if (ref) {
                let { init, init: { type, value } } = ref.path.node
                if (type === 'StringLiteral') {
                    expMap.set(name, value)
                } else if (type === 'TemplateLiteral') {
                    expMap.set(name, getResultFromTemplateLiteral(init, path))
                }
            } else {
                expMap.set(name, '')
            }
        }
    }

    return str = str.replace(/__(.*?)__/gim, name => expMap.get(name.replace(/__/g, '')))

    
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda