Skip to content

Instantly share code, notes, and snippets.

@axetroy
Created October 25, 2021 01:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save axetroy/9a076a7c1d88e45a1a6c6ac24844bfc7 to your computer and use it in GitHub Desktop.
Save axetroy/9a076a7c1d88e45a1a6c6ac24844bfc7 to your computer and use it in GitHub Desktop.
Babel plugin demo
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)
// 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