gpt4 book ai didi

javascript - 如何基于 AST 转换生成 JavaScript sourcemap?

转载 作者:行者123 更新时间:2023-11-29 14:38:43 26 4
gpt4 key购买 nike

假设我用 AST 将 JavaScript 文件的内容从状态 A 转换为状态 B。

如何制作随附的源 map ?我正在使用 esprimaestravese (estraverse.replace) 来遍历一个 AST(我有对应于初始 AST 的源图)并将其转换为另一个 AST(但我没有生成的 sourcemap)。

我怎样才能得到那个 sourcemap?

编辑:我正在使用 esprimaestraverse做我的 AST 转换。我的转变看起来像这样:

module.exports = {

type: 'replace', // or traverse

enter(node, parent) {

if (
node.type == 'ExpressionStatement'
&& parent.type == 'Program'
&& node.expression.type == 'CallExpression'
&& node.expression.callee.name == 'module'
) {
// rename `module` to `define`
node.expression.callee.name = 'define'

// The dependency object (the `{a:'./a', b:'./b'}` in `module({a:'./a', b:'./b'}, function(imports) {})`) will be...
const dependenciesObjectExpression = node.expression.arguments[0]

// ...converted into an array of paths (the `['./a', './b']` in `define(['./a', './b'], function(a,b) {})`), and...
const dependencyPathLiterals =
dependenciesObjectExpression.properties.map(prop => prop.value)

// ...the dependency names will be converted into parameters of the module body function (the `a,b` in `define(['./a', './b'], function(a,b) {})`).
const dependencyNameIdentifiers =
dependenciesObjectExpression.properties.map(prop => prop.key)

// set the new define call's arguments
node.expression.arguments[0] = {
type: 'ArrayExpression',
elements: dependencyPathLiterals,
}
node.expression.arguments[1].params = dependencyNameIdentifiers

return node
}

// if we see `imports.foo`, convert to `foo`
if (
node.type == 'MemberExpression'
&& node.object.type == 'Identifier'
&& node.object.name == 'imports'
) {
return {
type: 'Identifier',
name: node.property.name,
}
}
},

leave(node, parent) {
//
}

}

最佳答案

对于您编写的每个树转换,您都在源映射上编写了相应的转换。

因为树变换本质上是任意的,相应的源变换也将是任意的。同样,复杂的树转换将导致相应的复杂源映射转换。

实现此目的的一种方法可能是增选(我假设这些存在)树转换操作 DeleteNode、ReplaceNode、ReplaceChildWithIdentifier、ReplaceChildWithLiteral、ReplaceChildWithOperator。仅使用这些操作,您应该仍然能够对树进行任意更改。通过修改这些操作来更新源映射(每一个都对源映射做一些非常具体的事情),您应该“免费”获得更新的源映射。显然,您不能使用其他树修改操作,除非它们是使用这些原语实现的。

社区中用于此目的的一些工具:

关于javascript - 如何基于 AST 转换生成 JavaScript sourcemap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41789175/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com