4

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

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

我怎样才能得到那个源图?

编辑:我正在使用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) {
        //
    }

}
4

1 回答 1

2

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

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

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

为此目的,社区中有几个工具:

于 2017-01-22T11:10:20.997 回答