Created
November 15, 2017 13:51
-
-
Save erukiti/2e2a4561c1245d12df63a213829cdef2 to your computer and use it in GitHub Desktop.
templateを使ったヤツ、ソース中一回しか有効にならない件
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) | |
} | |
const addJsDoc = (nodePath, text) => { | |
const comments = ['/**', ...text.split('\n').map(line => ` * ${line}`), ' */\n'] | |
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