假设我 AST 将 JavaScript 文件的内容从状态 A 转换为状态 B。
我如何制作随附的源地图?我正在使用esprima
and estravese
(estraverse.replace) 来遍历一个 AST(我有对应于初始 AST 的源映射)并将其转换为另一个 AST(但我没有生成的源映射)。
我怎样才能得到那个源图?
编辑:我正在使用esprima和estraverse进行 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) {
//
}
}