Last active
October 20, 2016 17:41
-
-
Save sirbrillig/bac6b5d7ed1e78d4106a6ec461f936ba to your computer and use it in GitHub Desktop.
Babel plugin to convert simple React components to PHP
This file contains hidden or 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
module.exports = function( babel ) { | |
const t = babel.types; | |
let insertedPhp = false; | |
const updateParamNameVisitor = { | |
Identifier( path ) { | |
if ( path.node.name.startsWith( '$' ) ) { | |
return; | |
} | |
// Transform VariableDeclarator Identifiers to PHP style | |
path.replaceWith( t.identifier( '$' + path.node.name ) ); | |
}, | |
MemberExpression( path ) { | |
// Transform point reference syntax to thin arrow syntax | |
path.replaceWith( t.expressionStatement( t.identifier( `${path.node.object.name}->${path.node.property.name};` ) ) ); | |
} | |
}; | |
return { | |
visitor: { | |
BinaryExpression( path ) { | |
if ( t.isStringLiteral( path.node.left ) && path.node.operator === '+' ) { | |
// Transform string concat operator to PHP style | |
path.node.operator = '.'; | |
} | |
path.traverse( updateParamNameVisitor ); | |
}, | |
VariableDeclaration( path ) { | |
if ( ! insertedPhp ) { | |
// Add `<?php` expression | |
path.insertBefore( t.expressionStatement( t.identifier( '<?php ' ) ) ); | |
insertedPhp = true; | |
return; | |
} | |
// Replace VariableDeclaration with PHP VariableDeclaration | |
path.replaceWith( path.node.declarations[0] ); | |
}, | |
VariableDeclarator( path ) { | |
// Transform VariableDeclarator into PHP style | |
if ( path.node.id.name.startsWith( '$' ) ) { | |
return; | |
} | |
if ( t.isFunctionExpression( path.node.init ) ) { | |
return; | |
} | |
path.replaceWith( t.variableDeclarator( t.identifier( '$' + path.node.id.name ), path.node.init ) ); | |
path.traverse( updateParamNameVisitor ); | |
}, | |
FunctionExpression( path ) { | |
// Transform FunctionExpression to FunctionDeclaration | |
// Also remove VariableDeclaration for FunctionExpression | |
path.parentPath.parentPath.replaceWith( t.functionDeclaration( path.parentPath.node.id, path.node.params, path.node.body ) ); | |
}, | |
FunctionDeclaration( path ) { | |
// Transform FunctionDeclaration variables to PHP style | |
path.node.params = path.node.params.map( function( param ) { | |
param.name = '$' + param.name; | |
return param; | |
} ); | |
} | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment