[AST Babel] Create a simple babel plugin
For example, we have the source code:
getVersison(‘3.4.5‘) function getVersion(versionString) { const versionRegex = /(\d)\.(\d)\.(\d+)/ const [, major, minor, patch] = versionRegex.exec(versionString) return {major, minor, patch} }
We want to transform it into:
const _versionRegex = /(\d)\.(\d)\.(\d+)/; getVersison(‘3.4.5‘) function getVersion(versionString) { const [, major, minor, patch] = _versionRegex.exec(versionString) return {major, minor, patch} }
Babel plugin:
export default function (babel) { const { types: t } = babel; return { name: "ast-transform", // not required visitor: { RegExpLiteral(path) { const name = path.parent.id.name; //versionRege const newIdentifier = path.scope.generateUidIdentifier(name) // _versionRegex const variableDeclaration = t.variableDeclaration(‘const‘, [ t.variableDeclarator(newIdentifier, path.node) ]) // const _versionRegex = /(\d)\.(\d)\.(\d+)/; console.log(variableDeclaration) /* - const [, major, minor, patch] = versionRegex.exec(versionString) + const [, major, minor, patch] = _versionRegex.exec(versionString) */ path.scope.rename(name, newIdentifier.name) const program = path.findParent( t.isProgram ) console.log(program.node.body) program.node.body.unshift(variableDeclaration) // + const _versionRegex = /(\d)\.(\d)\.(\d+)/; path.parentPath.remove() // - const versionRegex = /(\d)\.(\d)\.(\d+)/ } } }; }
相关推荐
zhongweinan 2020-02-21
往后余生 2020-09-17
CXsilent 2020-09-16
webgm 2020-08-16
Lophole 2020-06-28
sqliang 2020-06-14
xcguoyu 2020-06-13
徐建岗网络管理 2020-06-11
前端开发Kingcean 2020-06-11
cbao 2020-06-10
yezitoo 2020-06-06
bigname 2020-06-04
前端开发Kingcean 2020-05-29
xiaofanguan 2020-05-29
ELEMENTS爱乐小超 2020-05-28
皖林 2020-05-11
wbczyh 2020-05-03