JavaScriptファイルの内容を状態Aから状態BにAST変換するとします。AST変換に基づいてJavaScriptソースマップを生成するにはどうすればよいですか?
付随するソースマップを作成するにはどうすればよいですか?私はesprima
とestravese
(estraverse.replace)を使用してASTをトラバースしています(最初のASTに対応するソースマップがあります)、別のASTに変換します(ただし、結果のソースマップはありません)。
どうすればそのソースマップを入手できますか?
EDIT:AST変換を行うにはesprimaとestraverseを使用しています。
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) {
//
}
}
"sourcemap" とは何ですか? –
... aha:定義されているソースマップ:https://www.html5rocks.com/en/tutorials/developertools/sourcemaps/ –