Created
November 15, 2017 13:57
-
-
Save erukiti/eed4e478582d990800cb96f8639451cc to your computer and use it in GitHub Desktop.
結論: 素直に NodePath の addComment 使え
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 assert = require('assert') | |
const src = | |
`function hoge(a: number): number { | |
return a | |
} | |
function fuga(a: string): string { | |
return a | |
} | |
` | |
const addLeadingComment = (nodePath, comment) => { | |
// const temp = `${comment}\n${nodePath.getSource()}` | |
// const ast = template(temp, {preserveComments: true, plugins: ['flow']})() | |
// nodePath.replaceWith(ast) | |
nodePath.addComment('leading', comment) | |
} | |
const addJsDoc = (nodePath, text) => { | |
const comments = ['*', ...text.split('\n').map(line => ` * ${line}`), ' '] | |
return addLeadingComment(nodePath, comments.join('\n')) | |
} | |
const plugin = (babel) => { | |
const toParam = nodePath => { | |
assert(nodePath.type === 'Identifier') | |
let typeAnnotation = '' | |
if (nodePath.node.typeAnnotation) { | |
typeAnnotation = `{${nodePath.get('typeAnnotation.typeAnnotation').getSource()}} ` | |
} | |
return `@param ${typeAnnotation}${nodePath.node.name} - parameter a` | |
} | |
const visitor = { | |
Function: { | |
exit: (nodePath, state) => { | |
console.log(nodePath.getStatementParent().node.leadingComments) | |
if (nodePath.getStatementParent().node.leadingComments) { | |
return | |
} | |
const comments = [] | |
nodePath.get('params').forEach(param => { | |
switch (param.type) { | |
case 'AssignmentPattern': { | |
comments.push(toParam(param.get('left'))) | |
break | |
} | |
case 'Identifier': { | |
comments.push(toParam(param)) | |
break | |
} | |
default: { | |
throw new Error(param) | |
} | |
} | |
}) | |
if (nodePath.node.returnType) { | |
comments.push(`@return {${nodePath.get('returnType.typeAnnotation').getSource()}}`) | |
} | |
addJsDoc(nodePath.getStatementParent(), comments.join('\n')) | |
} | |
} | |
} | |
return { | |
inherits: require('@babel/plugin-syntax-flow').default, | |
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