Created
January 19, 2021 20:27
-
-
Save ugultopu/3a789d77ebc94521300045022c1c4d83 to your computer and use it in GitHub Desktop.
A more readable printout of the example at https://github.com/jamiebuilds/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-traverse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const parser = require('@babel/parser'); | |
const traverse = require('@babel/traverse'); | |
// console.log('parser is', parser); | |
// console.log('traverse is', traverse); | |
const code = `function square(n) { | |
return n * n; | |
}`; | |
const ast = parser.parse(code); | |
logObjectWithMessage(ast, 'ast before traverse:'); | |
traverse.default(ast, { | |
enter(path) { | |
// logObjectWithMessage(path, 'path is:'); | |
if ( | |
path.node.type === 'Identifier' && | |
path.node.name === 'n' | |
) path.node.name = 'x'; | |
} | |
}); | |
logObjectWithMessage(ast, 'ast after traverse:'); | |
function logObjectWithMessage(object, message) { | |
removeProperties(object, ['start', 'end', 'loc']); | |
console.log(message); | |
console.log('='.repeat(message.length)); | |
console.dir(object, {depth: null}); | |
} | |
/** | |
* Recursively remove properties that: | |
* - Are `null` or `undefined` | |
* - Have 0 length | |
* - Have been listed in the `properties` parameter | |
* | |
* @param {Object} object - The object to remove the properties from. | |
* @param {String[]} properties - Names of properties to remove. | |
*/ | |
function removeProperties(object, properties) { | |
for (const property in object) { | |
const value = object[property]; | |
if (value == undefined) delete object[property]; | |
else if (value.length === 0) delete object[property]; | |
else if (properties.includes(property)) delete object[property]; | |
else if (value instanceof Object) removeProperties(value, properties); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment