Skip to content

Instantly share code, notes, and snippets.

@erukiti
Last active November 15, 2017 13:10
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 erukiti/ffb52e1b46b9456c9ee21ba93874ae23 to your computer and use it in GitHub Desktop.
Save erukiti/ffb52e1b46b9456c9ee21ba93874ae23 to your computer and use it in GitHub Desktop.
AST操作でコメント付与の実験
const template = require('babel-template')
const {parse} = require('babylon')
const {transform} = require('@babel/core')
const prettier = require('prettier')
const src =
`function hoge() {
}
`
const addLeadingComment = (nodePath, comment) => {
const temp = `${comment}\n${nodePath.getSource()}`
const ast = template(temp, {preserveComments: true})()
nodePath.replaceWith(ast)
}
const addJsDoc = (nodePath, text) => {
const comments = ['/**', ...text.split('\n').map(line => ` * ${line}`), ' */\n']
return addLeadingComment(nodePath, comments.join('\n'))
}
const plugin = (babel) => {
const visitor = {
Function: {
exit: (nodePath, state) => {
if (nodePath.node.leadingComments) {
return
}
addJsDoc(nodePath, 'hoge')
}
}
}
return {
visitor
}
}
let {code} = transform(src, {plugins: [plugin]})
// code = prettier.format(code)
console.log(code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment