Last active
November 15, 2017 13:10
-
-
Save erukiti/ffb52e1b46b9456c9ee21ba93874ae23 to your computer and use it in GitHub Desktop.
AST操作でコメント付与の実験
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 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