Created
October 25, 2021 01:25
-
-
Save axetroy/9a076a7c1d88e45a1a6c6ac24844bfc7 to your computer and use it in GitHub Desktop.
Babel plugin demo
This file contains 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 babel = require('babel-core') | |
const code = ` | |
const abc = 1 + 2 // foo | |
const defghijk = 3 + 4 // bar | |
` | |
const result = babel.transform(code, { | |
plugins: [require('./plugin')] | |
}) | |
console.log(result.code) |
This file contains 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
// var babel = require('babel-core') | |
// var t = require('babel-types') | |
/** | |
* | |
* @param { import('babel-core') } babel | |
* @returns | |
*/ | |
function myPlugin(babel) { | |
const { types: t } = babel | |
/** | |
* @typedef { Object } BabelPlugin | |
* @property { import('babel-traverse').Visitor } visitor | |
*/ | |
/** @type {BabelPlugin} */ | |
const plugin = { | |
visitor: { | |
VariableDeclaration(path) { | |
// path.node.id.name = path.node.id.name + ' ' | |
const nextPaths = [] | |
let prevPath = path | |
while (true) { | |
const next = path.getNextSibling() | |
if (!next || !next.node) { | |
break | |
} | |
if (prevPath.node.loc.start.line + 1 === next.node.loc.start.line) { | |
nextPaths.push(next) | |
prevPath = next | |
} else { | |
break | |
} | |
} | |
console.log(nextPaths) | |
} | |
} | |
} | |
return plugin | |
} | |
module.exports = myPlugin |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment